B · Structure · intermediate · Week 2–3 · Chapter 5 of 13
Files, JSON & pathlib
with open(...) for files. json.load/dump. pathlib.Path for cross-platform paths. Test data lives in JSON.
Path progress33%
Step 1 of 3
Read and write files
with open(path) as f: always closes the file. Specify encoding="utf-8" on Windows.
Example
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.
Was this step clear?
Chapter learning outcomes
- with open context manager
- json module
- pathlib.Path
- Reading test fixtures
Clear these before you leave
Side quest
Fixture reader
load_fixture(name) loads tests/fixtures/{name}.json.