Sub topic 2
Choosing a file mode
This chapter assumes you can write basic Python (variables, functions, loops), know the difference between str and bytes, and can use try/except. The with statement is covered in the next chapter. Here the examples use it without explanation, because it closes the file for you.
What a mode controls
The second argument of open() is the mode string. It sets four things at the moment the file is opened:
- Whether you may read, write, or both.
- Whether an existing file is kept or emptied.
- Whether a missing file is created or reported as an error.
- Whether you work with text (
str) or raw bytes (bytes).
If you leave the mode out, Python uses "r", which means read text. Most file bugs come from choosing a mode that quietly does something other than what you expected, so it pays to know exactly what each letter does.
The base modes
Every mode string contains exactly one of r, w, a, or x. This letter decides what happens to the file when you open it.
| Mode | Meaning | If the file exists | If the file is missing |
|---|---|---|---|
| `r` | Read | Opened, position at the start | `FileNotFoundError` |
| `w` | Write | **Emptied immediately** | Created |
| `a` | Append | Kept, writes go at the end | Created |
| `x` | Exclusive create, write | `FileExistsError` | Created |
The next sections go through each one.
`r`: read only
This is the default. The file must exist, and any call to write() fails.
with open("demo.txt", "w", encoding="utf-8") as f:
f.write("one\ntwo\n")
with open("demo.txt", "r", encoding="utf-8") as f:
print(f.readable(), f.writable())
try:
f.write("three\n")
except OSError as exc:
print(type(exc).__name__, exc)The output is True False, then UnsupportedOperation not writable. The exception is io.UnsupportedOperation, which inherits from both OSError and ValueError. Catching OSError is enough.
`w`: write and truncate
Opening with "w" deletes the existing contents at the moment of open(). It does not wait for your first write().
from pathlib import Path
with open("demo.txt", "w", encoding="utf-8") as f:
f.write("one\ntwo\n")
print(len(Path("demo.txt").read_bytes())) # 8
with open("demo.txt", "w", encoding="utf-8") as f:
pass # nothing written
print(len(Path("demo.txt").read_bytes())) # 0The second with block never calls write(), yet the file is now empty.
`a`: append
Append mode keeps the existing content and puts every write at the end of the file. It creates the file if it does not exist, which makes it a good fit for logs.
with open("log.txt", "a", encoding="utf-8") as f:
f.write("started\n")
with open("log.txt", "a", encoding="utf-8") as f:
f.write("finished\n")
with open("log.txt", encoding="utf-8") as f:
print(f.read())On every run, two more lines are added. In append mode the operating system forces each write to the end, even if you call seek() to move elsewhere. You cannot use append mode to overwrite the middle of a file.
`x`: create, never overwrite
Exclusive creation succeeds only if the file does not already exist. Otherwise it raises FileExistsError. The existence check and the creation are done as one operation by the operating system. That is safer than checking Path.exists() yourself and then opening with "w", because another process could create the file between your check and your open.
try:
with open("demo.txt", "x", encoding="utf-8") as f:
f.write("new content\n")
except FileExistsError:
print("demo.txt already exists, refusing to overwrite it")Use "x" for output files that must never replace earlier results, such as an export named with a date.
Modifiers: `b`, `t`, and `+`
The base letter can be combined with modifiers.
`t` and `b`: text or binary
t means text and is the default, so "r" and "rt" are the same. b means binary. The choice changes the type of the data and what Python does to it:
| Row | Text mode | Binary mode |
|---|---|---|
| Data type | `str` | `bytes` |
| Encoding | Applied, set with `encoding=` | None |
| Newline translation | Applied, set with `newline=` | None |
| Passing `encoding=` | Allowed | `ValueError` |
Mixing the types gives a TypeError:
with open("demo.bin", "wb") as f:
f.write(b"\x00\x01\x02")
try:
f.write("text")
except TypeError as exc:
print(exc) # a bytes-like object is required, not 'str'
with open("demo.bin", "rb") as f:
data = f.read()
print(data, type(data).__name__) # b'\x00\x01\x02' bytesUse binary mode for anything that is not plain text: images, archives, executables, and files whose encoding you do not control. Reading such a file in text mode can raise UnicodeDecodeError or alter bytes that look like newlines. Chunked binary reading has its own chapter later on.
`+`: update, read and write
Adding + makes the file both readable and writable. It does not change what the base letter does at open time. This is the part people most often get wrong.
| Mode | Readable and writable | Truncates on open | Missing file | Start position |
|---|---|---|---|---|
| `r+` | Yes | No | Error | Start |
| `w+` | Yes | **Yes** | Created | Start |
| `a+` | Yes | No | Created | End |
| `x+` | Yes | n/a | Created, error if present | Start |
r+ is the mode for editing a file in place. Writes go over the existing characters from the current position and do not insert:
with open("demo.txt", "w", encoding="utf-8") as f:
f.write("hello world\n")
with open("demo.txt", "r+", encoding="utf-8") as f:
f.write("J")
f.seek(0)
print(f.read()) # Jello worldThe H was replaced, and the rest was untouched. The seek(0) call moves the position back to the start so the read sees the whole file. Position handling gets its own chapter, so for now remember that reads and writes share one position.
a+ opens at the end, so a plain read() returns an empty string. Seek first:
with open("log.txt", "a+", encoding="utf-8") as f:
f.write("checked\n")
f.seek(0)
print(f.read())Combining letters
The order of the modifiers does not matter, so "r+b", "rb+" and "br+" are all accepted. The convention is the base letter first, then +, then b, or simply rb, wb, ab, xb. The pairings you will meet most often are:
"rb"and"wb"for copying or processing binary data."ab"for appending raw bytes to a file."r+b"for patching bytes in an existing binary file.
You cannot give two base letters. "rw" raises ValueError: must have exactly one of create/read/write/append mode. If you want to read and write, use +.
Inspecting an open file
A file object reports what its mode allows. This is useful when a function receives a file from its caller and must check that it can use it:
with open("demo.txt", "r+", encoding="utf-8") as f:
print(f.readable(), f.writable(), f.seekable())
print(f.mode)This prints True True True and then r+. The readable() and writable() methods are more reliable than parsing the mode string yourself, because they also work for objects that are not ordinary files, such as io.StringIO.
How to choose
Ask the questions in this order: do I need to keep what is already there, and what should happen if the file is missing?
After you pick the letter, add b if the data is not text. Then, for text, add encoding="utf-8" (or whichever encoding the file really uses) so the result does not depend on the machine's default.
Common mistakes
- Using
"w"to add a line. The file is emptied on every run. Use"a". - Using
"r+"and expecting insertion. It overwrites bytes in place. To insert, read the content, change it in memory, and write it back. - Writing a shorter value in
"r+". If the new text is shorter than the old text, the leftover tail stays in the file. Callf.truncate()after writing to cut the file at the current position. - Opening binary data as text. Decoding errors or silently changed line endings follow. Use
"rb". - Using
"w"when a missing directory is the real problem. No mode creates parent directories.open("out/result.txt", "w")raisesFileNotFoundErrorifoutdoes not exist.
Exercise
A script runs every night and must record one line of results in "results.txt". Earlier lines must be kept, and the file may not exist on the first night. Which mode do you use, and what goes wrong if you pick "w"? Then name the mode you would use if the script should instead stop with an error when "results.txt" already exists.
Show answer
Use "a" (with an explicit encoding). It keeps earlier lines, adds each new line at the end, and creates the file on the first run. With "w", every run empties the file when it is opened, so only the latest line survives. To refuse to touch an existing file, use "x", which raises FileExistsError.
Exercise
A file contains "abcdef". You run open(path, "r+") and call write("XY") and then close the file. What does the file contain afterwards? What would it contain if you had opened it with "w+" and written "XY"?
Show answer
With "r+" the file contains "XYcdef", because writing starts at position 0 and overwrites the first two characters without truncating. With "w+" the file is emptied on open, so it contains only "XY".