Programming foundations

Stage 6 · Lesson 3 of 8

Files, JSON and pathlib

Build and ship your first projects

JSON in Python is the job of the json module. It turns JSON text into dictionaries and lists, and back again. json.load(f) reads from an open file and json.dump(data, f, indent=2) writes to one.

pathlib.Path makes file paths work on every , as in Path("data") / "ledger.json". Path.exists() lets you create a starter file on the first run. For safely, open them with encoding="utf-8".

Validate what you load: data["amount"] raises KeyError when the key is missing, and "12.50" is a string, not a float. For tables of data, the csv module handles quoted values that a plain split(",") gets wrong. Keep loading and saving in their own , so the core logic receives plain dictionaries.

A question to check yourself, an AI practice session and 2 cheat sheet entries come when you add the roadmap to your account. Add it

Resources for this stage

Start with· follow one of these

Keep handy

  • Free APIs that give a small project real data to work with

Also worth your time

Mark this stage as not done?