Lesson 152 of 1455
Python File I/O
Reading and writing files is where real scripts start. Learn the with-statement, path handling, and JSON round-trips.
Builders · AI-Assisted Coding · ~18 min read
pathlib Is the Answer
Skip `os.path` and string concatenation. `pathlib.Path` handles cross-platform paths, reads, writes, and checks existence in one object.
write_text / read_text handle open, close, and encoding. Safer than raw open().
from pathlib import Path import json data_dir = Path("data") data_dir.mkdir(exist_ok=True) record = {"user": "Ada", "score": 91} out = data_dir / "record.json" out.write_text(json.dumps(record, indent=2), encoding="utf-8") loaded = json.loads(out.read_text(encoding="utf-8")) print(loaded["score"]) # 91Line-by-line for big files
Iterating a file streams one line at a time — no memory blowups on huge logs.
with open("big.log", encoding="utf-8") as f: errors = [line for line in f if "ERROR" in line] print(f"found {len(errors)} errors")Understanding "Python File I/O" in practice: AI can help you write, fix, and understand code faster than ever — even if you're just learning. Reading and writing files is where real scripts start. Learn the with-statement, path handling, and JSON round-trips — and knowing how to apply this gives you a concrete advantage.
- Apply pathlib in your ai-coding workflow to get better results
- Apply with in your ai-coding workflow to get better results
- Apply json in your ai-coding workflow to get better results
- Apply encoding in your ai-coding workflow to get better results
- 1Use AI to generate unit tests for an existing function
- 2Ask AI to refactor a messy function and explain the changes
- 3Have AI suggest a code review for a recent pull request
Key terms in this lesson
The big idea: pathlib for paths, context managers for safety, explicit utf-8 everywhere. That covers nine out of ten I/O tasks.
End-of-lesson quiz
Check what stuck
8 questions · Score saves to your progress.
Lesson help
Questions are best handled with a grown-up here.
For this age range, Tendril keeps freeform AI chat paused until parent/guardian consent and child-safe moderation are fully verified. Use the quiz, notes, and related lessons below, or ask a parent, guardian, teacher, or librarian to work through the question with you.
Progress saved locally in this browser. Sign in to sync across devices.
Related lessons
Keep going
Builders · 35 min
Tests as Prompts — an Unexpected Superpower
Writing a test first is not just good engineering. It is the clearest possible prompt for an AI. Let's use tests to make AI code reliable.
Builders · 35 min
SQL Basics With AI
SELECT, WHERE, JOIN, GROUP BY. Four keywords run the data world. AI is excellent at SQL because it has read every StackOverflow answer ever.
Builders · 25 min
What Does AI-Assisted Coding Even Mean?
AI-assisted coding is not magic and not cheating. It is a new way of working where a model drafts, you decide. Let's draw a map before we start building.
