Lesson 152 of 1570
Python File I/O
Reading and writing files is where real scripts start. Learn the with-statement, path handling, and JSON round-trips.
Lesson map
What this lesson covers
Learning path
The main moves in order
- 1pathlib Is the Answer
- 2pathlib
- 3with
- 4json
Concept cluster
Terms to connect while reading
Section 1
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
15 questions · Score saves to your progress.
Tutor
Curious about “Python File I/O”?
Ask anything about this lesson. I’ll answer using just what you’re reading — short, friendly, grounded.
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.
