Skip to content
Ruby

File I/O

Read, write, append, traverse directories, and process CSV files.

By EZ4Code Team
fileiocsv

Code

# Write text
File.write("data.txt", "line 1\nline 2\n")

# Read entire file
puts File.read("data.txt")

# Read line by line (auto-closes)
File.foreach("data.txt") { |line| puts "[#{line.chomp}]" }

# Append
File.open("data.txt", "a") { |f| f.puts "line 3" }

# File info
puts File.exist?("data.txt")
puts File.size("data.txt")

# Path operations
puts File.basename("/a/b/c.txt")       # c.txt
puts File.dirname("/a/b/c.txt")        # /a/b
puts File.extname("c.txt")             # .txt
puts File.join("a", "b", "c.txt")

# Directory traversal
Dir.mkdir("samples") unless Dir.exist?("samples")
Dir.glob("*.txt").each { |f| puts f }

# CSV with stdlib
require "csv"
CSV.open("people.csv", "w") do |csv|
  csv << %w[name age]
  csv << ["Alice", 30]
end

CSV.foreach("people.csv", headers: true) do |row|
  puts "#{row['name']} is #{row['age']}"
end

Explanation

File.write and File.read cover one-shot text I/O, while File.foreach streams large files line by line without loading them into memory. The block form of File.open closes the handle automatically even on errors. The csv stdlib handles both writing rows and reading with headers out of the box.

More Ruby Snippets