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:
Syntax
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
File.write("greeting.txt", "Hello from File.write!")
content = File.read("greeting.txt")
puts content
Login to try C/C++/Java/PHP code in the editor
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
- Reading a file that does not exist, which raises
Errno::ENOENT. - Expecting
File.writeto append, when it overwrites the file's contents. - 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: