Reading & Writing Files
Lesson 3 of 5 · View course roadmap
Learn the idea
Files persist data beyond your program's run. The golden pattern is with open(...) — it closes the file automatically, even if an error occurs:
with open("data.txt", "w") as f:— write mode (creates/overwrites)"a"— append mode;"r"— read (the default)f.write("text")— note: you add your own\nf.read()— whole file;for line in f:— line by line (memory-friendly)line.strip()— remove the trailing newline when reading
Where you'll use this
Log writers, report generators, config loaders, data pipelines — file I/O is the connective tissue of ops and data work. The with-statement pattern here is verbatim what runs in production.
Common mistakes
- Opening with
"w"when you meant"a"— write mode instantly erases the existing file, no confirmation. - Forgetting newlines:
f.write("line")does not add\n— unlike print. - Reading numbers and forgetting they're strings-with-newlines: always
int(line.strip()). - Hardcoded absolute paths that break on any other machine — use relative paths or pathlib.
Pro tip
pathlib makes quick jobs one-liners: Path("notes.txt").read_text() and Path("out.txt").write_text(data) — no open/close ceremony at all.
Try it yourself
The lesson example is loaded and ready — press Run, then change something and run it again. Breaking it is part of learning. Want a clean slate? Tap “New blank”.
Output appears here…
Pass the challenge +30 XP
Write the numbers 1–5 to a file nums.txt, one per line. Then read it back and print the sum of the numbers.
15
Write f"{i}\n" in a loop; when reading, int(line.strip()) each line.
with open("nums.txt", "w") as f:
for i in range(1, 6):
f.write(f"{i}\n")
total = 0
with open("nums.txt") as f:
for line in f:
total += int(line.strip())
print(total)
Run your code to check it…
Check your understanding
Your notes (saved on this device)
Tip: use ← and → to move between lessons, ⌘K to search everything.