Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

Ruby Dictionary

  1. Home
  2. Ruby Dictionary
  3. File.read / write / open

File.read / write / open

Methods for reading and writing files. Use File.read to read the entire contents, and File.write to write to a file.

Syntax

# Reads the entire file contents as a string.
content = File.read("file_path")
content = File.read("file_path", encoding: "UTF-8")

# Writes a string to a file (overwrites existing content).
File.write("file_path", content)

# Opens a file and operates on it within a block (automatically closed).
File.open("file_path", "mode") do |f|
  # File operations
end

# Reads the file line by line.
File.foreach("file_path") { |line| process }

Open Modes

ModeDescription
"r"Opens for reading only (default). Raises an error if the file does not exist.
"w"Opens for writing only. Truncates the file if it already exists.
"a"Opens in append mode. Adds content to the end of the file.
"r+"Opens for reading and writing. Raises an error if the file does not exist.
"w+"Opens for reading and writing. Truncates the file if it already exists.

Sample Code

# Writes to a file.
File.write("sample.txt", "Hello, Ruby!\nThis is line 1.\n")
puts "Write complete"

# Reads the file contents.
content = File.read("sample.txt")
puts content

# Uses File.open with a block for safe file handling.
File.open("log.txt", "a") do |f|
  f.puts "#{Time.now}: Log entry appended."
end

# Reads and processes the file line by line.
File.open("sample.txt", "r") do |f|
  f.each_line.with_index(1) do |line, number|
    puts "Line #{number}: #{line.chomp}"
  end
end

# Processes line by line with foreach (returns an enumerator without a block).
line_count = File.foreach("sample.txt").count
puts "Line count: #{line_count}"

Notes

File operations in Ruby are performed through the File class. For small files, File.read and File.write are the most concise options. Using File.open with a block automatically closes the file when the block finishes, preventing you from forgetting to close it.

If you use File.open without a block, you must call close explicitly. Leaving a file open prevents resources from being released, which can cause problems when handling a large number of files. When reading large files all at once, memory usage increases, so consider using foreach to process the file line by line instead.

If you find any errors or copyright issues, please .