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

File.read and File.write

In this page:

  1. File.read and File.write

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
🔒

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.