Loading lesson…
Reading and writing files is where real scripts start. Learn the with-statement, path handling, and JSON round-trips.
Skip `os.path` and string concatenation. `pathlib.Path` handles cross-platform paths, reads, writes, and checks existence in one object.
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"]) # 91write_text / read_text handle open, close, and encoding. Safer than raw open().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")Iterating a file streams one line at a time — no memory blowups on huge logs.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.
The big idea: pathlib for paths, context managers for safety, explicit utf-8 everywhere. That covers nine out of ten I/O tasks.
15 questions · take it digitally for instant feedback at tendril.neural-forge.io/learn/quiz/end-progx-python-file-io-builders
Why is it recommended to use pathlib.Path instead of string concatenation when building file paths?
On a Windows computer, a script writes emoji to a file using the default encoding. What likely happens?
A CSV file contains a quoted field like: "Doe, John". What happens if you parse it using .split(',')?
What is the main purpose of the 'with' statement when opening files in Python?
Which Python module is recommended for properly parsing CSV files with quoted fields containing commas?
What problem does explicitly specifying encoding='utf-8' solve?
What happens if you forget to close a file after opening it with open() but without a 'with' statement?
A student builds a path like 'data/' + 'folder/' + 'file.txt'. Why might this cause problems on Windows?
What is a key advantage of pathlib.Path.write_text() compared to manually opening and writing files?
Why might reading a 10GB log file all at once cause problems?
What does pathlib.Path.exists() return when checking a file path?
Which of these is a correct reason to use the csv.DictReader class?
A Python script runs on Linux but produces files that Windows users say are corrupted. What is the most likely cause?
What does the 'with' statement guarantee when used with file operations?
Why is Path('folder') / 'file.txt' preferred over 'folder/' + 'file.txt'?