Day 16 of 30Real Python & Data
💾Files: Read & Write
🎯 Today's objective
Persist data by reading and writing files.
📖 Key concepts
- open() with a mode: "r", "w", "a"
- Use with open(...) as f (auto-closes)
- f.read(), f.readlines(), f.write()
- Text vs CSV files
💻 Try this code
with open("notes.txt", "w") as f:
f.write("Day 16: files!\n")
with open("notes.txt") as f:
print(f.read())👥 Learn it your way
🧒 Young Explorers
Files let your program remember things after it closes — like saving a game.
Your task
Save a to-do list (one item per line) to a file, then read it back and print it.
💼 Professionals
Always use context managers; know encoding (utf-8) and the csv module for tabular data.
Your task
Append a timestamped log line to a file each run; read and print the last 3 lines.
🤖 AI connection
Datasets live in files (CSV, JSON, images). Loading data from disk is literally step one of every machine-learning project.
✅ Quick check
What does mode "a" do?
Appends to the end of a file (without erasing it).
Why use `with open(...)`?
It automatically closes the file, even on error.