File Modes
Python · File Handling
Theory
The second argument to open() is the mode, a short string that sets what you can do with the file and what happens to it on opening. 'r' reads (the default; the file must exist). 'w' writes, creating the file or erasing its contents. 'a' appends to the end, creating the file if needed. 'x' creates a new file and fails if it already exists. Adding '+' allows both reading and writing: 'r+' reads and writes without erasing, while 'w+' erases first.
Adding 'b' switches from text to binary mode: 'rb' and 'wb' work with raw bytes instead of strings, with no encoding or newline translation. Binary is needed for images, PDFs, Excel files and pickles. So open('data.csv', 'r') reads text, open('photo.png', 'rb') reads bytes and open('log.txt', 'a') appends text.
Why we use it
Choosing the right mode prevents nasty surprises, like wiping a file with 'w' when you meant to add to it, or corrupting an image by opening it as text.
When to use it
Ask two questions: read, write or append? Text or binary? Use 'r' to read, 'a' to keep history, 'w' only when replacing is intended, 'x' to avoid accidental overwrites, and add 'b' for any non-text file.
How it works
- Choose a mode for open()
- Only reading? Yes: Use 'r' (or 'rb' for binary). No: Decide how to write.
- Keep existing content? Yes: 'a' appends, 'r+' edits. No: 'w' replaces, 'x' refuses to overwrite.
- Is the file non-text (image, PDF)? Yes: Add 'b', e.g. 'wb'. No: Stay in text mode.
- Open the file with the chosen mode
Syntax
open(path, mode)
# 'r' 'w' 'a' 'r+' 'rb' 'wb'Example
open('data.csv', 'r') # read text
open('data.bin', 'rb') # read binary
open('log.txt', 'a') # append textKey points
- Add 'b' for binary mode (images, non-text data)
- r+ allows both reading and writing without truncating first
- 'w' and 'w+' erase the file the moment it is opened
- 'x' creates a file and raises FileExistsError if it exists
- 'r' raises FileNotFoundError when the file is missing