Skip to lesson content
navan✳THE BUILD LABPYTHON 3
0/101 complete
BUILD LAB / PYTHON/ Into the real world
EXPERIMENT 20 / 101

Give your script a memory.

Write and read text with explicit encoding and predictable cleanup.

BY NAVAN SAMI◷ 6 MIN READPYTHON 3

01 The idea

Files let information survive after a process ends. Use a with statement to manage an open file: it closes the file when the block finishes, including when an exception occurs. Specify an encoding for text so your intention is clear across environments.

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.

files.py
from pathlib import Path

path = Path("lab-notes.txt")
with path.open("w", encoding="utf-8") as file:
    file.write("Build. Test. Learn.\n")

with path.open("r", encoding="utf-8") as file:
    print(file.read().strip())
↳ EXPECTED OUTPUT
Build. Test. Learn.

03 Under the hood

  1. 1

    The write mode "w" creates the file if needed and truncates an existing file. This example writes in your current working directory.

  2. 2

    The context manager closes the first handle before the second with block opens the file for reading.

  3. 3

    read() loads the text into memory. For a large file, loop over the file object to process one line at a time. Append mode "a" adds text at the end instead of replacing existing content.

04 Your turn, builder

A SMALL MISSION

Write "One useful idea" to idea.txt, then read and print the text.

Reveal one possible solution +
one_possible_solution.py
from pathlib import Path

path = Path("idea.txt")
path.write_text("One useful idea", encoding="utf-8")
print(path.read_text(encoding="utf-8"))

05 Check your signal

QUICK SIGNAL CHECK

What does opening an existing file in "w" mode do?

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.