Manuals / Python / Chapter 5

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 progress
33%

Step 1 of 3

Read and write files

with open(path) as f: always closes the file. Specify encoding="utf-8" on Windows.

Read and write filesDrag stickies · tap for tips
Study mapDrag stickies · tap for tipsKeep it shortdrag · tap →Name the waitdrag · tap →Scope locatorsdrag · tap →Trace when stuckdrag · tap →One browser firstdrag · tap →Isolate statedrag · tap →Assert the UIdrag · tap →Retry wiselydrag · tap →Seed datadrag · tap →Close the loopdrag · tap →Keep it shortdrag · tap →Name the waitdrag · tap →Scope locatorsdrag · tap →Trace when stuckdrag · tap →One browser firstdrag · tap →Isolate statedrag · tap →Pathwise hackdrag · tap →Read and write fildrag · tap →Try thisdrag · tap →Follow the dashed drag · tap →

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.