Give your script a memory.
Write and read text with explicit encoding and predictable cleanup.
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.
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())Build. Test. Learn.
03 Under the hood
- 1
The write mode "w" creates the file if needed and truncates an existing file. This example writes in your current working directory.
- 2
The context manager closes the first handle before the second with block opens the file for reading.
- 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
Write "One useful idea" to idea.txt, then read and print the text.
Reveal one possible solution +
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
What does opening an existing file in "w" mode do?
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 ↗.