Locked lesson.
About this lesson
There are several "modes" for opening files. Learn them all here.
Exercise files
Download this lesson’s related exercise files.
Open File Modes - Solution.docx59.2 KB Open File Modes.docx
57.7 KB
Quick reference
Open File Modes
There are several ways to open files, depending on what you want to do with them.
When to use
Use any of these open file modes depending on what type of thing you wish to do with the file.
Instructions
Here's a list of open file modes:
r Read only, pointer at beginning of file
r+ Read-Write, pointer at beginning of file
w Write-Only, erases old file contents
w+ Read-Write, erases old file contents
a Write-Only, pointer at end of file
a+ Read-Write, pointer at end of file
To use a specific mode, just pass it in as a parameter in the File.open() method:
my_file = File.new("file.txt", "a+")
Hints & tips
- r, r+, w, w+, a, a+
- Stay away from w and w+ unless you want to erase what's already on a file!
Lesson notes are only available for subscribers.