Skip to content
Tutorials Center
My learning

Topics

Lesson 75 of 134 · Standard Library

Files and IO

Learn to read and write files in Ruby with File and IO - open with blocks, modes, line-by-line reading, paths, directories, globbing and handling file errors.

Almost every real program talks to the outside world through files: configuration, data, logs, output. Ruby wraps the operating system's file calls in two friendly classes. IO is the general idea of "something you can read bytes from or write bytes to" (files, pipes, sockets, the keyboard). File is the subclass of IO that works with files on disk, and Dir works with directories.

On this site your code runs on a server in a temporary working directory that is deleted after each run. That is perfect for learning: every example creates the files it needs, reads them back and leaves nothing behind. In your own projects the same code works on real files. You will meet the safer temporary-file tools in Tempfile, Pathname and FileUtils, and the in-memory equivalent in StringIO and Streams.

Writing and reading whole files

For small files, two class methods do everything: File.write and File.read.

Ruby File.write and File.read

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

File.write creates the file (or replaces it if it exists) and returns the number of bytes written. File.read returns the whole file as one string. File.readlines returns an array of lines, and chomp: true removes the trailing newlines. These are ideal for configuration and small data files. For a file bigger than memory they are the wrong tool; read it line by line instead, as shown below.

Opening files with a block

For more control, use File.open. Always give it a block. Ruby closes the file when the block ends, even if an exception is raised inside. Without the block you must remember to call close, and a forgotten close can leak file handles or leave data unflushed.

Ruby File.open with modes

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The most common modes are:

Mode Meaning
"r" read only (the default); the file must exist
"w" write; creates the file or truncates it to empty
"a" append; creates the file if needed, writes at the end
"r+" read and write, starting at the beginning, no truncation
"w+" read and write, truncating first
"b" suffix binary mode, as in "rb" or "wb"

puts adds a newline, print does not, << returns the file so calls can be chained, and write returns the number of bytes. Reading methods keep a position in the file: gets reads the next line, read(5) reads five bytes from the current position, eof? reports the end, and rewind jumps back to the start.

Mode "w" destroys the existing contents the moment you open the file, even if you write nothing. Use "a" to add to a file and "w" only when you really mean to start over.

Reading line by line

A file read with each_line holds only one line in memory at a time, so it works for gigabytes. File.foreach is the shortcut that opens, iterates and closes in one call. Without a block they return an enumerator, which means the whole Enumerable toolbox works, and lazy keeps it memory-friendly.

Ruby foreach, each_line and lazy processing

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The third example turns the file into an enumerator, so map and select chain naturally. In .lazy.map(&:chomp).first(2) the file is read only until two lines have been produced, which is how you peek at the start of a huge file.

Paths: File.join, basename and friends

Never build paths by gluing strings with "/". Use the File helpers, which handle separators and edge cases for you.

Ruby Working with path strings

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

File.join removes duplicated separators. basename returns the last part, extname the extension including the dot, and dirname everything before the last part. File.expand_path resolves .. and relative names against a base directory, and without a base uses the current directory. __FILE__ is the name of the running file and __dir__ its directory, which is how scripts find files that live next to them.

Directories

Dir lists, creates and searches directories. Dir.glob takes shell-like patterns: * matches within one directory level, ** goes through all subdirectories, and {a,b} lists alternatives.

Ruby Dir.mkdir, children and glob

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Dir.children lists names without the . and .. entries that Dir.entries includes. The order of directory listing is up to the operating system, so sort it whenever the output matters. Dir.chdir with a block changes the working directory only inside the block and then restores it, which is the safe way to do it. File.rename moves or renames, and File.delete removes one file. Removing a directory with all its contents is the job of FileUtils.rm_rf, covered in the next lesson.

The Dir class in depth

The example above used Dir briefly. It is a small class with two faces: class methods that work with a directory by name (Dir.mkdir, Dir.children, Dir.glob), and instance methods on an open directory handle (Dir.new or Dir.open), which let you step through entries one at a time like a file. The class methods cover most everyday work.

Task Method
Does it exist? Is it empty? Dir.exist?(path), Dir.empty?(path)
Create / remove one directory Dir.mkdir(path), Dir.rmdir(path) (only when empty)
Current directory Dir.pwd (alias Dir.getwd), Dir.chdir(path) { ... }
List names Dir.children, Dir.each_child, Dir.entries
Find by pattern Dir.glob(pattern) or Dir[pattern]
Special places Dir.home, Dir.tmpdir (after require "tmpdir")

Three listing methods are easy to mix up. Dir.entries returns every name including "." (this directory) and ".." (its parent). Dir.children returns the same names without those two, which is almost always what you want. Dir.each_child does the same lazily: with a block it yields each name, without one it returns an enumerator. None of them returns the full path, only the names, and the order is up to the file system.

Ruby Dir class methods: create, list, glob, remove

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Notice how the failures show up: creating a directory that exists raises Errno::EEXIST, a missing parent raises Errno::ENOENT (Dir.mkdir creates one level only; FileUtils.mkdir_p creates the chain), and removing a directory that still has files raises Errno::ENOTEMPTY. Glob patterns work like this: * matches any run of characters within one level, ? matches one character, [ot] matches one character from a set, **/ descends through subdirectories, and {rb,md} offers alternatives. A * never matches a name that starts with a dot unless you pass File::FNM_DOTMATCH. The base: option searches inside a directory and returns paths relative to it. Dir.chdir with a block yields the path, changes the working directory only for the block and restores it afterwards. The process-wide working directory is shared by all threads, so avoid chdir in threaded programs and use full paths there.

Dir instances

Dir.new(path) opens a directory handle. You then read names one at a time with read, which returns nil at the end, and move around with tell, seek(pos) and rewind. path returns the name you opened, fileno the operating-system descriptor, and close releases it; any use after closing raises IOError. As with files, Dir.open(path) { |dir| ... } closes the handle for you. A handle also has each, each_child and children, with the same meaning as the class methods.

Ruby Reading a directory handle and a temporary directory

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Dir.mktmpdir (from the tmpdir library) is the right tool for tests and scratch work: it creates a uniquely named directory under Dir.tmpdir and deletes it with its contents when the block ends. Dir.home returns the current user's home directory. For paths as objects with methods instead of strings, see Tempfile and Pathname.

When files go wrong

Files fail often, and the operating system explains why with a specific exception. They all live under SystemCallError as Errno::... classes.

Ruby Opening a file that is not there (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The program stops with main.rb:2:in 'IO.read': No such file or directory @ rb_sysopen - settings.conf (Errno::ENOENT). The text after @ names the failing system call and the path. Rescue the specific error and decide what to do: use a default, create the file, or report to the user.

Ruby Rescuing file errors

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Keep two families apart. Errno::... errors come from the operating system (missing file, permission denied, is a directory, disk full). IOError is raised by Ruby itself when you misuse a handle: writing to a read-only file, or reading from a closed one. A rescue list should name the specific errors you can handle and let everything else propagate.

A safe pattern for "write a file without ever leaving it half-written" is to write to a temporary name and rename it over the target. File.rename is atomic on the same file system, so readers see either the old file or the new one:

Ruby Atomic replace with rename

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

File inquiries and low-level reads

Before you open a file you can ask questions about it. These class methods do not raise for a missing file; they answer false, so they make safe guards.

Ruby Asking about a file

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

sysread(n) reads at most n bytes with no Ruby-level buffering and raises EOFError at the end of the file, whereas read(n) returns nil there. Do not mix sysread with buffered methods such as gets or read on the same handle: the buffer and the file position get out of step. For everyday work stick to read, each_line and readlines.

Binary files and encodings

Text mode converts line endings on some systems and tags strings with an encoding. For images, archives and other binary data open the file with "rb" / "wb" and work with bytes.

Ruby Binary mode and bytes

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

File.binread returns a string tagged BINARY (the old name is ASCII-8BIT, and Ruby 4.0 prints both), where one character is one byte. The text héllo has five characters but six bytes, so File.read reports 5 while binread reports 6. Mixing up the two is the usual cause of corrupted images and broken downloads.

Standard streams

Your program always has three open streams: $stdin (or STDIN), $stdout and $stderr. They are IO objects like any file, so everything above applies. puts is just $stdout.puts. Send diagnostics to $stderr so that normal output can be piped to another program without them.

Ruby stdout, stderr and IO objects

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

File descriptors 0, 1 and 2 are stdin, stdout and stderr on every Unix-like system. sync = true turns off output buffering so text appears immediately.

Check your understanding

Quick check · 5 questions

of 5 answered You scored / 5 · perfect!

  1. 1. What happens to an existing file when you open it with mode "w"?

    Mode w truncates the file to zero length as soon as it is opened. Use mode a to append.
  2. 2. Why should you pass a block to File.open?

    The block form guarantees the file is closed, which avoids leaked handles and unflushed data.
  3. 3. Which approach reads a very large file without loading it all into memory?

    foreach (and each_line) hold one line at a time. read, readlines and binread load everything.
  4. 4. Which exception is raised by File.read("nope.txt") when the file does not exist?

    Operating-system errors are Errno::* classes. ENOENT means no such file or directory.
  5. 5. What does File.basename("a/b/report.txt", ".*") return?

    basename returns the last path component, and the second argument ".*" strips any extension.

Summary

  • File.write, File.read and File.readlines handle small files in one call; File.foreach and each_line stream big ones.
  • Use File.open(path, mode) { |f| ... } so the file is always closed; "w" truncates, "a" appends.
  • Build paths with File.join, take them apart with basename, extname and dirname, and resolve them with File.expand_path.
  • Dir.children, Dir.glob, Dir.mkdir, File.rename and File.delete manage the file system; sort listings.
  • OS errors are Errno::... (subclasses of SystemCallError); misuse of a handle raises IOError.
  • Open binary data with "rb" / "wb" or binread / binwrite; characters and bytes differ for UTF-8.
  • Write important files atomically with a temporary file and File.rename.

Next: Tempfile, Pathname and FileUtils