TExcelTAD
Home › Ruby › Ruby File I/O

Ruby File I/O

Reading and writing files is one of Ruby's everyday jobs: processing logs, generating reports, importing CSV data. The File class (with its relatives Dir, IO and FileUtils) makes this short and safe.

Note: The playgrounds run in a temporary sandbox directory, so the examples below really create and read files. Each run starts with an empty folder, which is why every example writes its file first.

Writing and reading a whole file

ruby · try it yourself
File.write("notes.txt", "Buy milk\nCall Sam\nWater plants\n")

content = File.read("notes.txt")
puts content
p content.length
p File.exist?("notes.txt")
p File.size("notes.txt")
Buy milk
Call Sam
Water plants
31
true
31

File.write creates the file (or replaces it) and returns the number of bytes written. File.read returns the whole content as one string — ideal for small files.

Reading line by line

For larger files, process one line at a time so the whole file never has to be in memory:

ruby · try it yourself
File.write("todo.txt", "write report\nfix bug #12\n\nreview PR\n")

File.foreach("todo.txt").with_index(1) do |line, number|
  next if line.strip.empty?
  puts "#{number}: #{line.chomp}"
end

lines = File.readlines("todo.txt", chomp: true)
p lines
p lines.reject(&:empty?).size
1: write report
2: fix bug #12
4: review PR
["write report", "fix bug #12", "", "review PR"]
3

chomp: true removes the trailing newline from every line.

File.open with a block

File.open gives you a file object. With a block, Ruby closes the file automatically when the block ends — even if an exception is raised:

ruby · try it yourself
File.open("log.txt", "w") do |f|
  f.puts "server started"
  f.puts "listening on port 8080"
  f.print "status: ", "ok", "\n"
  f << "done" << "\n"
end

File.open("log.txt", "a") { |f| f.puts "appended later" }

File.open("log.txt") do |f|
  puts f.gets           # read one line
  puts f.read.upcase    # read the rest
end
server started
LISTENING ON PORT 8080
STATUS: OK
DONE
APPENDED LATER

File modes

Mode Meaning If the file exists If it doesn't
"r" read (default) read from the start error
"w" write emptied first created
"a" append write at the end created
"r+" read and write from the start error
"w+" / "a+" read and write like w / a created

Tip: Always prefer the block form of File.open. Without a block you must call f.close yourself, and forgetting it can leave data unwritten.

Handling missing files

ruby · try it yourself
begin
  File.read("missing.txt")
rescue Errno::ENOENT => e
  puts "Could not read: #{e.class}"
end

path = "settings.conf"
config = File.exist?(path) ? File.read(path) : "defaults"
p config
Could not read: Errno::ENOENT
"defaults"

Operating-system errors live in the Errno module; ENOENT means "no such file or directory".

Paths and file information

ruby · try it yourself
path = "reports/2025/summary.final.csv"
p File.basename(path)
p File.basename(path, ".csv")
p File.extname(path)
p File.dirname(path)
p File.join("data", "users", "list.txt")

File.write("info.txt", "abc")
p File.file?("info.txt")
p File.directory?("info.txt")
p File.zero?("info.txt")
"summary.final.csv"
"summary.final"
".csv"
"reports/2025"
"data/users/list.txt"
true
false
false

Directories

ruby · try it yourself
require "fileutils"

FileUtils.mkdir_p("project/src")
File.write("project/src/app.rb", "puts 1")
File.write("project/src/util.rb", "puts 2")
File.write("project/README.md", "# demo")

p Dir.exist?("project/src")
p Dir.children("project").sort
p Dir.glob("project/**/*.rb").sort

FileUtils.rm_rf("project")
p Dir.exist?("project")
true
["README.md", "src"]
["project/src/app.rb", "project/src/util.rb"]
false

Dir.glob with ** searches subdirectories recursively; FileUtils provides mkdir_p, cp, mv and rm_rf.

A small CSV example

Ruby ships a csv library for reading and writing comma-separated files:

ruby · try it yourself
require "csv"

CSV.open("scores.csv", "w") do |csv|
  csv << ["name", "score"]
  csv << ["Mina", 88]
  csv << ["Theo", 72]
  csv << ["Ravi", 95]
end

rows = CSV.read("scores.csv", headers: true)
rows.each { |r| puts "#{r['name']}: #{r['score']}" }
best = rows.max_by { |r| r["score"].to_i }
puts "Best: #{best['name']}"
Mina: 88
Theo: 72
Ravi: 95
Best: Ravi

With headers: true, each row behaves like a hash keyed by the column names. All values come back as strings — convert with to_i/to_f.

Test yourself

What does opening a file with mode "w" do if the file already exists?

  1. Appends to it
  2. Raises an error
  3. Empties it before writing
  4. Opens it read-only

Why prefer File.open(path) { |f| ... } over f = File.open(path)?

  1. It is faster
  2. The file is closed automatically
  3. It can read binary files
  4. It creates missing directories

Which method reads a file line by line without loading it all at once?

  1. File.read
  2. File.foreach
  3. File.write
  4. File.size