Open Modes
Lesson 4 of 12 in Coddy's File Handling in Python course.
You can also specify mode of operation in the open function with open(filename, operation).
There are four different modes for opening a file:
| Mode | Key | Description |
|---|---|---|
| Read | 'r' | Opens a file for reading |
| Append | 'a' | Opens a file for appending |
| Write | 'w' | Opens a file for writing |
| Create | 'x' | Creates the specified file |
Note: if the file does not exists all the modes will create the file except the read mode
You can also specify if the file should be handled in binary or text mode:
| Mode | Key | Description |
|---|---|---|
| Text | 't' | Text mode |
| Binary | 'b' | Binary mode |
Some examples:
- Open a file named data.csv in append mode
open('data.csv', 'a') - Open a file named foo.txt in write and binary mode
open('foo.txt', 'wb') - Open a file named bar.txt in read and write mode
open('bar.txt', 'rw')
The default open mode is
'rt', soopen('a.txt')is the same asopen('a.txt', 'rt')
Try it yourself
This lesson doesn't include a code challenge.