Free lab Real Python 3. Zero installs. Your code stays in this browser. Open the playground

Reading & Writing Files

14 min 30 XP
Study loop Read Predict Run Tweak Prove Review
Lesson 3 of 5 · View course roadmap
Step 1

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 \n
  • f.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.

Step 2

Try it yourself

Blank · autosaved

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”.

PYexample.py
+ Enter to run
Output appears here…
Step 3

Pass the challenge +30 XP

Blank · autosaved

Write the numbers 1–5 to a file nums.txt, one per line. Then read it back and print the sum of the numbers.

Target output
15
PYchallenge.py
Run your code to check it…
Step 4

Check your understanding

1. Why prefer `with open(...)` over open()/close()?
2. Mode "w" on an existing file will…
Last step

Your notes (saved on this device)

Tip: use and to move between lessons, K to search everything.

Your next ten minutes

Write Python that does something useful.

Start free. No install, no card, no passive video marathon.

Start learning free → Explore the path