Ruby example

How to write to a file in Ruby

9 min read Updated Dec 2026 Runs in an isolated runtime
Quick answer

Use File.write: File.write("notes.txt", "Hello\n") creates the file, or replaces what was in it, and returns the number of bytes written. Add mode: "a" to append instead. To write in several steps, open the file with a block, which closes it for you: File.open("notes.txt", "w") { |f| f.puts "Hello" }.

Ruby's File.write is the equivalent of Python's Path.write_text and Node's fs.writeFileSync, and File.open with a block plays the part of Python's with open(…). The sections below cover writing a whole string with File.write, writing line by line in a File.open block, what each open mode does, creating a directory only when it is missing, moving, renaming and deleting files, and writing CSV and JSON, then a table of the calls and modes. Every example reads its file back in the same program to show what landed on disk; files written here are removed when the run ends. Each example runs on this page: hit Run, then edit the code and run it again.

1File.write: the whole file in one callRecommended

File.write(path, text) opens the file, writes the string, closes it and returns the number of bytes written. If the file does not exist it is created; if it does, its old contents are replaced. Pass mode: "a" to add to the end instead. Anything that is not a string is converted with to_s, and no newline is added for you, so end the text with "\n" yourself. Writing an empty string is the simplest way to create an empty file.

file_write.rb
# Write a whole string: creates the file or replaces its contents
bytes = File.write("notes.txt", "first line\nsecond line\n")
p bytes
p File.read("notes.txt")

# mode: "a" appends instead of replacing
File.write("notes.txt", "third line\n", mode: "a")
puts File.read("notes.txt")

# Without mode:, the old contents are gone
File.write("notes.txt", "fresh start\n")
p File.read("notes.txt")

# Create an empty file
File.write("empty.txt", "")
p File.exist?("empty.txt")
p File.size("empty.txt")

# Non-strings are written with to_s
File.write("count.txt", 42)
p File.read("count.txt")

# Several lines: join them and end with a newline
lines = ["alpha", "beta", "gamma"]
File.write("words.txt", lines.join("\n") + "\n")
p File.readlines("words.txt", chomp: true)

p Dir.children(".").sort

Output

The first write returns 23, the byte count of the two lines. The append adds third line after them, and the next plain File.write leaves only "fresh start\n": without a mode, every call starts the file over. The empty file exists with size 0, and 42 comes back as the string "42", since a file holds text, not numbers. The last line lists the working directory; main.rb is this page's own script. To read the lines back one at a time, see read a file line by line.

2File.open with a block: puts, write, print and <<

When the content comes in pieces, from a loop or several calls, open the file once with File.open(path, "w") do |f| … end and write to f. The file object has the same output methods as $stdout: puts adds a newline after each argument (and after each element of an array), write and print add nothing, << can be chained, and printf formats. When the block ends, even through an exception, Ruby closes the file and returns the block's value. Without a block, File.open returns the open file and closing it is your job.

file_open_block.rb
File.open("report.txt", "w") do |f|
  f.puts "Report"
  f.puts "a", "b"
  f.puts ["x", "y"]
  f.write "no newline", "|"
  f.print "print adds none either\n"
  f << "chained " << 3 << "\n"
  f.printf("%-6s|%5.2f\n", "pi", 3.14159)
end
puts File.read("report.txt")

# The block's value comes back, and the file is closed
result = File.open("small.txt", "w") { |f| f.write("abc") }
p result
p File.read("small.txt")

# Without a block, close the file yourself
f = File.open("log.txt", "w")
f.write "hello"
p File.read("log.txt")
f.close
p File.read("log.txt")
p f.closed?

Output

f.puts ["x", "y"] writes two lines, while write runs no newline| straight into the print text, and << turns 3 into text. The block returns 3, the value of its last call (write's byte count). The last part shows why closing matters: right after f.write "hello", reading the file gives "" because the text is still in Ruby's buffer; after f.close it reads "hello". Call f.flush to push the buffer out without closing. Prefer the block form, and File.write when one string is enough.

3File.open modes: "w", "a", "r+", "w+", "a+" and "wx"

The second argument to File.open (or the mode: keyword) says what to do with the file. "w" creates or empties it, "a" creates it or keeps it and writes at the end, "r+" reads and writes an existing file from the start without emptying it, "w+" and "a+" are "w" and "a" plus reading, and an x added to "w" refuses to touch a file that already exists. Add b ("wb") for binary data, and pass encoding: to choose how text is stored. The default mode, "r", is read-only.

open_modes.rb
File.write("data.txt", "0123456789\n")

# "a": every write goes to the end
File.open("data.txt", "a") { |f| f.puts "appended" }
p File.read("data.txt")

# "r+": read and write from the start; nothing is cut off
File.open("data.txt", "r+") { |f| f.write "AB" }
p File.read("data.txt")

# "w+": empty the file, then write and read
File.open("data.txt", "w+") do |f|
  f.puts "new"
  f.rewind
  p f.read
end

# "a+": reads start at the top, writes still go to the end
File.open("data.txt", "a+") do |f|
  p f.read
  f.puts "more"
end
p File.read("data.txt")

# "wx": create a new file, fail if it already exists
begin
  File.open("data.txt", "wx") { |f| f.puts "never written" }
rescue Errno::EEXIST => e
  puts "#{e.class}: #{e.message}"
end

# "r" (the default) is read-only
begin
  File.open("data.txt", "r") { |f| f.write "x" }
rescue IOError => e
  puts "#{e.class}: #{e.message}"
end

# Keyword form, with an explicit encoding
File.open("cafe.txt", mode: "w", encoding: "UTF-8") { |f| f.puts "café" }
p File.read("cafe.txt")
p File.size("cafe.txt")

Output

"r+" overwrote the first two characters in place, giving "AB23456789\nappended\n"; the rest of the file stayed. In "w+", rewind moves back to the start so the write can be read, and "a+" read the whole file before its write landed at the end. The exclusive mode raised Errno::EEXIST: File exists @ rb_sysopen - data.txt and left the file alone; on its own, "x" is not a mode (ArgumentError: invalid access mode x), so write it as "wx". Writing to a file opened with "r" fails with IOError: not opened for writing, and opening a missing file with "r+" raises Errno::ENOENT. The word café takes 6 bytes in UTF-8, because é uses two.

4Create a directory if it does not exist

Dir.exist?(path) and File.directory?(path) both tell you whether a directory is there; File.exist? is true for files and directories alike, and File.file? only for regular files. Dir.mkdir creates one directory and raises if it already exists or if its parent is missing. FileUtils.mkdir_p (from require 'fileutils', like mkdir -p) creates every missing level and does nothing when the directory is already there, which makes it the usual answer. Writing a file into a directory that does not exist fails, so create the directory first.

make_directories.rb
require 'fileutils'

# Is it there, and is it a directory?
p Dir.exist?("logs")
Dir.mkdir("logs") unless Dir.exist?("logs")
p Dir.exist?("logs")
p File.directory?("logs")
p File.exist?("logs")
p File.file?("logs")

# Dir.mkdir fails if it exists, or if the parent is missing
begin
  Dir.mkdir("logs")
rescue Errno::EEXIST => e
  puts e.message
end
begin
  Dir.mkdir("out/2026/12")
rescue Errno::ENOENT => e
  puts e.message
end

# mkdir_p creates every missing level, and is safe to repeat
FileUtils.mkdir_p("out/2026/12")
FileUtils.mkdir_p("out/2026/12")
p Dir.glob("out/**/*").sort

# Writing into a missing directory fails...
path = File.join("data", "cache", "item.json")
begin
  File.write(path, "{}")
rescue Errno::ENOENT => e
  puts e.message
end

# ...so create the file's directory first
FileUtils.mkdir_p(File.dirname(path))
File.write(path, "{}")
p File.exist?(path)
p Dir.children(".").sort

Output

Before Dir.mkdir, Dir.exist?("logs") is false; after it, the directory answers true to Dir.exist?, File.directory? and File.exist?, and false to File.file?. A second Dir.mkdir raises File exists @ dir_s_mkdir - logs, and a nested path with missing parents raises No such file or directory. Calling mkdir_p twice is fine, and Dir.glob shows both levels it made. File.dirname turns data/cache/item.json into the directory to create, the common pattern before saving a file to a nested path.

5Move, rename, copy and delete files

File.rename(from, to) renames or moves a file within the same disk. FileUtils.mv does the same, accepts a directory as the target, and also moves between disks or mounts, where File.rename fails. Copy with FileUtils.cp and delete with File.delete (or FileUtils.rm). Renaming onto an existing file replaces it without a warning, which is also how you swap in a new version of a file safely: write a temporary file next to it, then rename it over the old one.

move_files.rb
require 'fileutils'

File.write("draft.txt", "hello\n")

# Rename in place
File.rename("draft.txt", "final.txt")
p Dir.children(".").sort

# Move into a directory
FileUtils.mkdir_p("archive")
FileUtils.mv("final.txt", "archive/")
p Dir.children("archive")

# Copy, then delete the copy
FileUtils.cp("archive/final.txt", "copy.txt")
p File.read("copy.txt")
File.delete("copy.txt")
p File.exist?("copy.txt")

# Renaming onto an existing file replaces it
File.write("settings.txt", "v1\n")
File.write("settings.txt.tmp", "v2\n")
File.rename("settings.txt.tmp", "settings.txt")
p File.read("settings.txt")

# A missing source raises Errno::ENOENT
begin
  File.rename("nope.txt", "x.txt")
rescue Errno::ENOENT => e
  puts e.message
end

p Dir.children(".").sort

Output

After the rename only final.txt is left next to main.rb, and the move puts it in archive. The copy reads back "hello\n" and is gone after File.delete. The settings.txt lines show the safe-replace pattern: the file now holds "v2\n", and a reader never sees it half written, because a rename on the same disk happens in one step. A missing source raises No such file or directory @ rb_file_s_rename - (nope.txt, x.txt). To remove a directory and everything in it, use FileUtils.rm_rf.

6Write CSV and JSON

For CSV, require 'csv' and use CSV.open, which takes the same modes as File.open; each csv << row writes one array as one line and quotes fields that contain commas. For JSON, require 'json', turn the data into a string with JSON.generate or JSON.pretty_generate, and save it with File.write.

csv_and_json.rb
require 'csv'
require 'json'

rows = [
  ["Ann", 31, "London, UK"],
  ["Bob", 41, "Lisbon"]
]

CSV.open("people.csv", "w") do |csv|
  csv << ["name", "age", "city"]
  rows.each { |row| csv << row }
end
puts File.read("people.csv")

# Append one more row
CSV.open("people.csv", "a") { |csv| csv << ["Cy", 25, nil] }
puts File.read("people.csv").lines.last

config = { "name" => "app", "debug" => false, "ports" => [80, 443] }
File.write("config.json", JSON.pretty_generate(config))
puts File.read("config.json")
p JSON.parse(File.read("config.json")) == config

Output

"London, UK" is written in quotes because it contains a comma, numbers are written as plain text, and nil becomes an empty field (Cy,25,). The "a" mode added a row without rewriting the header. JSON.pretty_generate indents with two spaces, and parsing the file back gives a hash equal to the original, so the last line prints true.

7Which should you use?

Call or modeFile missingFile existsBest for
File.write(path, text)CreatedReplacedWriting a whole file at once: most cases
File.write(path, text, mode: "a")CreatedAdded to the endAdding a line to a log
File.open(path, "w") { |f| … }CreatedEmptied firstMany writes: loops, puts, printf
"a"CreatedKept, writes at the endAppending many lines
"r+"Errno::ENOENTKept, overwritten from the startChanging bytes in place
"w+"CreatedEmptied firstWriting, then reading back
"a+"CreatedKept, writes at the endReading and appending
"wx"CreatedErrno::EEXISTNever overwriting an existing file
"r" (default)Errno::ENOENTRead onlyReading, not writing

Frequently asked questions

How do I create a new file in Ruby?

Write to it: File.write("new.txt", "") creates an empty file (or empties an existing one). FileUtils.touch("new.txt") creates it when missing and leaves an existing file's contents alone, updating only its timestamp. To create a file only if it does not exist yet, open it with "wx", which raises Errno::EEXIST otherwise.

What is the difference between puts, print, write and << on a file?

They all write text. puts adds a newline after each argument (and each array element) unless the text already ends with one. print and write add nothing; write returns the number of bytes written. << adds nothing and returns the file, so calls can be chained: f << "a" << "b".

Do I have to close the file?

Not with File.write or File.open with a block: both close the file for you, the block form even when an exception is raised. With f = File.open(path, "w") you must call f.close; until then the text may still be in Ruby's buffer, so another reader can see an empty file. f.flush writes the buffer out without closing.

How do I write to a temporary file?

The standard library has Tempfile (require 'tempfile') for a single file and Dir.mktmpdir for a directory; both pick a unique name in the system temp directory and can clean up after themselves. They aren't available on this page, so the examples here write into the current directory, whose files are removed when the run ends.

How do I write binary data to a file?

Use File.binwrite(path, data) or open with "wb". Binary mode writes bytes as they are, with no encoding conversion and no newline translation on Windows. For example, File.binwrite("x.bin", [0, 255].pack("C*")) writes 2 bytes, and File.binread("x.bin").bytes gives [0, 255].

Is File.write the same as IO.write?

Yes. File is a subclass of IO, and File.write is the IO.write class method inherited by it, so both take the same arguments (mode:, encoding:, an offset). Most Ruby code writes File.write because it reads as a file operation; IO.write in an older answer does the same thing.

Run it yourself

Open any of these in the full Ruby editor to tweak, run and share.

Ruby playground