Python Essentials for AI Engineer

Course Content

Python Essentials for AI Engineer

6 sections · 48 lessons

What are the different file modes in Python?


What open() does before you write a byteFileNotFoundErrorreads from the startcreates ittruncates to emptycreates itkeeps it,writes at endcreates itFileExistsErrorFile missingFile existsrwax
Only w destroys data, and it does so the moment open() runs — even if the loop that should write never executes.

What you need to know

The four base modes

ModeIf the file is missingIf the file existsWrites go
r (default)FileNotFoundErroropens for reading—
wcreates ittruncates it to emptyfrom the start
acreates itkeeps contentalways at the end
xcreates itFileExistsErrorfrom the start

Then combine with:

  • t — text (the default): you read and write str; Python encodes and decodes using encoding= and translates line endings.
  • b — binary: you read and write bytes, 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
with open("notes.txt", "w", encoding="utf-8") as f:    f.write("run 1\n")with open("notes.txt", "a", encoding="utf-8") as f:    f.write("run 2\n")with open("notes.txt", encoding="utf-8") as f:       # mode "r" by default    print(f.read().splitlines())                    # ['run 1', 'run 2']try:    open("notes.txt", "x")except FileExistsError as e:    print(type(e).__name__)                          # FileExistsErrorwith open("notes.txt", "rb") as f:    print(f.read(5))                                 # b'run 1' -> bytes, not str

A 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
from datetime import datetimerun_file = f"results-{datetime.now():%Y%m%d-%H%M%S}.jsonl"with open(run_file, "x", encoding="utf-8") as f:    # fails loudly instead of overwriting    f.write('{"case": 1, "passed": true}\n')print(run_file.startswith("results-"))              # True

Follow-up questions to expect

  • "What is the difference between r+ and w+?" — 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 encoding in binary mode?" — No; it raises ValueError. Bytes have no encoding until you decode them.