← Back to Ruby Course | Chapter 11: File I/O & Exceptions | Lesson 1 of 6

File.read and File.write

File.read opens a file and hands you all its text, and File.write saves text into a file. It is like reading a whole letter or writing a fresh one.

In this page:

  1. File.read and File.write
Syntax
ruby
content = File.read("path")
File.write("path", content)

File.read and File.write

File.read("path") reads an entire file's contents into a single string in one call, the simplest way to load a small-to-medium text file.

File.write("path", content) writes a string to a file, creating or overwriting it. Both are convenient class-level methods for simple, one-shot file operations.

Note: File.write overwrites the entire file by default -- there's no separate append mode without extra options.

Example: File.read and File.write

markup
File.write("greeting.txt", "Hello from File.write!")

content = File.read("greeting.txt")
puts content
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Reading a file that does not exist, which raises Errno::ENOENT.
  2. Expecting File.write to append, when it overwrites the file's contents.
  3. Using a relative path and looking for the file in the wrong folder, since it is relative to the working directory.
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.