Course Content
Python Essentials for AI Engineer
6 sections · 48 lessons
What are the different file modes in Python?
What you need to know
The four base modes
| Mode | If the file is missing | If the file exists | Writes go |
|---|---|---|---|
r (default) | FileNotFoundError | opens for reading | — |
w | creates it | truncates it to empty | from the start |
a | creates it | keeps content | always at the end |
x | creates it | FileExistsError | from the start |
Then combine with:
t— text (the default): you read and writestr; Python encodes and decodes usingencoding=and translates line endings.b— binary: you read and writebytes, exactly as stored. Use it for images, PDFs, audio, pickles and model files.+— also allow the other direction:r+reads and writes without truncating,w+truncates then allows reading,a+reads anywhere but always writes at the end.
Python
1with open("notes.txt", "w", encoding="utf-8") as f:2 f.write("run 1\n")3with open("notes.txt", "a", encoding="utf-8") as f:4 f.write("run 2\n")5with open("notes.txt", encoding="utf-8") as f: # mode "r" by default6 print(f.read().splitlines()) # ['run 1', 'run 2']78try:9 open("notes.txt", "x")10except FileExistsError as e:11 print(type(e).__name__) # FileExistsError1213with open("notes.txt", "rb") as f:14 print(f.read(5)) # b'run 1' -> bytes, not strA real-life example
An evaluation script records one line per test case in results.jsonl. It opens the file with w. Every time someone reruns the script to test one prompt change, two weeks of earlier results are wiped, and the team cannot compare against the old baseline.
The fix depends on what you want. If each run should add to a history, use a. If each run should get its own file and never overwrite, build a unique name and use x, which refuses to clobber anything:
Python
1from datetime import datetime23run_file = f"results-{datetime.now():%Y%m%d-%H%M%S}.jsonl"4with open(run_file, "x", encoding="utf-8") as f: # fails loudly instead of overwriting5 f.write('{"case": 1, "passed": true}\n')6print(run_file.startswith("results-")) # TrueFollow-up questions to expect
- "What is the difference between
r+andw+?" — Both read and write.r+needs the file to exist and keeps its content;w+creates or truncates it first. - "When do you use binary mode?" — For anything that is not text: images, audio, PDFs, pickles, model weights — or when you need the exact bytes, like computing a file hash.
- "Can you pass
encodingin binary mode?" — No; it raisesValueError. Bytes have no encoding until you decode them.