Skip to lesson content
navan✳THE BUILD LABPYTHON 3
0/101 complete
BUILD LAB / PYTHON/ Files with a future
EXPERIMENT 28 / 101

Open with intention.

Choose read, write, append, or exclusive creation and understand what each can change.

ADVANCED LAB
BY NAVAN SAMI◷ 10 MIN READPYTHON 3

01 The idea

File modes are a data-preservation decision. Read mode expects an existing file; write mode creates or truncates; append adds at the end; exclusive mode creates only if the path is absent. Text streams translate bytes using an encoding. UTF-8 is a useful explicit choice for your own text formats, but imported files may require a documented different encoding.

02 The experiment

Read it once. Predict what will happen. Then copy it into a .py file and run it in your local Python setup.

file_modes_encoding.py
from pathlib import Path
path = Path("mission.log")
with path.open("w", encoding="utf-8") as stream:
    stream.write("Launch\n")
with path.open("a", encoding="utf-8") as stream:
    stream.write("Landed\n")
with path.open("r", encoding="utf-8") as stream:
    print(stream.read(), end="")
↳ EXPECTED OUTPUT
Launch
Landed

03 Under the hood

  1. 1

    The first block deliberately starts a fresh practice log. Opening in w would erase an older version, so that decision belongs at the program boundary.

  2. 2

    The append block retains the first message. A with block closes the stream on success or failure; it is not a transaction or a guarantee against simultaneous writers.

  3. 3

    For new-file-only behaviour choose x and handle FileExistsError. Use binary modes such as rb when bytes must not undergo text decoding or newline conversion.

04 Your turn, builder

A SMALL MISSION

Create an exclusive new file and report if the path already exists.

Reveal one possible solution +
one_possible_solution.py
from pathlib import Path
path = Path("fresh-note.txt")
try:
    with path.open("x", encoding="utf-8") as stream:
        stream.write("One intentional write")
except FileExistsError:
    print("Already exists")
else:
    print("Created")

05 Check your signal

QUICK SIGNAL CHECK

Which mode refuses to overwrite an existing file?

THAT’S ANOTHER IDEA IN YOUR TOOLKIT.

Experiment. Logged.

When you can explain the idea and make the example your own, mark it complete. Your log stays in this browser.

Keep exploring

Go deeper with the official Python guide ↗.

Built with curiosity. By Navan Sami. ↗Python 3 · Think. Try. Build.