Sub topic 2
Choosing a file mode
This chapter assumes you know basic Python syntax, the difference between str and bytes, and how try/except works. The with statement is covered in the next chapter, so the examples here use it without explaining it.
What a mode controls
The second argument to open() is the mode string. It decides three things:
- Whether you can read, write, or both.
- What happens to the file's existing content when it is opened.
- Whether you work with text (
str) or raw bytes (bytes).
If you leave the mode out, Python uses "r", which means read text.
The mode letters
| Mode | Meaning | Missing file | Existing content |
|---|---|---|---|
| `r` | Read only (default) | `FileNotFoundError` | Kept |
| `w` | Write only | Created | Erased on open |
| `a` | Append only | Created | Kept, writes go to the end |
| `x` | Create and write | Created | `FileExistsError` if the file exists |
| `+` | Add reading and writing to another mode | Same as the base mode | Same as the base mode |
| `b` | Binary mode: `bytes` instead of `str` | Same as the base mode | Same as the base mode |
| `t` | Text mode (default) | Same as the base mode | Same as the base mode |
You combine one of r, w, a, x with optional + and b. For example, "rb" reads bytes, "wb" writes bytes, and "r+" reads and writes text.
Write mode erases the file
The most common mistake is using "w" on a file you meant to keep. Python truncates the file to zero length at the moment open() runs, before you write anything.
with open("notes.txt", "w", encoding="utf-8") as f:
f.write("first line\n")
with open("notes.txt", "w", encoding="utf-8") as f:
pass # nothing written, but the file is now empty
with open("notes.txt", encoding="utf-8") as f:
print(repr(f.read())) # ''Use "a" when you want to add to the end of a file:
with open("notes.txt", "a", encoding="utf-8") as f:
f.write("appended line\n")In append mode every write goes to the end of the file, even if you call seek() first.
Refusing to overwrite with x
Mode "x" is exclusive creation. It is the safe choice when overwriting would be a bug, such as when you write a report with a generated name.
try:
with open("report.txt", "x", encoding="utf-8") as f:
f.write("draft\n")
except FileExistsError:
print("report.txt already exists, not overwriting")The first run creates the file. Every later run prints the message.
Adding + for both directions
Adding + makes the file readable and writable, but the three base modes still differ in how the file starts:
"r+"starts with the existing content intact and the position at the start. The file must already exist."w+"erases the file first, then lets you write and read back."a+"keeps the content, writes at the end, and lets you read after aseek(0).
Switching between reading and writing on one file object is easy to get wrong. Most programs are simpler if they read the file in one with block and write it in another.
Text mode versus binary mode
Text mode decodes bytes into str using an encoding and translates line endings. Binary mode does neither. The mode decides which type write() accepts:
with open("data.bin", "wb") as f:
f.write(b"\x00\x01\x02") # bytes: correct
with open("data.bin", "wb") as f:
f.write("hello") # TypeError: a bytes-like object is requiredThe reverse also fails. Writing bytes to a file opened in text mode raises TypeError: write() argument must be str, not bytes. Use binary mode for images, archives, and any file you copy without interpreting it. Binary mode takes no encoding argument, so passing one raises ValueError.
A quick way to decide
Common errors
FileNotFoundErrorwith"r","r+": the path is wrong, or the file has not been created yet.- Empty file after a run: you used
"w"where"a"was needed. FileExistsErrorwith"x": the file is already there, which is the mode working as intended.ValueError: must have exactly one of create/read/write/append mode: the string contains two base letters, such as"rw". Use"r+"instead.
Exercise
A log file named app.log must keep all earlier lines, and each run of your script should add one new line at the end. Which mode do you pass to open(), and what happens to the old content if you choose "w" by mistake?
Show answer
Use "a" (append). With "w", open() truncates the file to zero length immediately, so all earlier log lines are lost before your script writes anything.