Locked lesson.
About this lesson
We'll learn to write and append data to a file.
Exercise files
Download this lesson’s related exercise files.
Write to a File - Solution.docx59.3 KB Write to a File.docx
59 KB
Quick reference
Write to a File
Let's write to a file!
When to use
Writing to a file is easy, you just need to determing whether you want to write to the beginning or end of the file.
Instructions
To write to a file, choose the appropriate open mode so that you can write to the file at either the beginning or end of the file.
Writing to the beginning, use r
Writing to the end, use a
Want to erase the old contents first, use w
To add something to a file, just puts it to the file variable:
my_file = File.open("some_file.txt", "r")
my_file.puts "Some Text to add"
Hints & tips
- Write to the beginning, r
- Write to the end, a
Lesson notes are only available for subscribers.