B · StructureIntermediate40 min read
5. Files, JSON & pathlib
Python · 52 pages source format
with open(...) for files. json.load/dump. pathlib.Path for cross-platform paths. Test data lives in JSON.
What you'll learn
- with open context manager
- json module
- pathlib.Path
- Reading test fixtures
Read and write files
with open(path) as f: always closes the file. Specify encoding="utf-8" on Windows.
import json
with open("users.json", encoding="utf-8") as f:
users = json.load(f)
for u in users:
print(u["username"])Do this now
Write users.json with 3 users. Load in Python and print usernames.
Clear?
pathlib
Path("data/users.json") / "subdir" — cleaner than os.path.join.
Do this now
Refactor file paths to use pathlib.Path.
Clear?
Write JSON output
json.dump(data, f, indent=2) for readable output files from glue scripts.
Do this now
Script: read CSV or JSON → transform → write summary.json.
Clear?