Checkpoint

Checkpoint: The Repeatable Import

The Guild's master ledger lives in ledger.json. It's a dict that maps each row's id to the row itself:

{"A1": {"id": "A1", "item": "oil", "qty": "3"}}

Importing by id makes reruns safe. Each import also reports what it did: how many rows were added (new id), updated (same id, different data) or unchanged.

Saving without losing data

If the program crashes halfway through writing ledger.json, the file could be left half-written. So write to a temporary file first, then swap it in:

tmp = path.with_suffix(".tmp")
tmp.write_text(json.dumps(ledger, indent=2, sort_keys=True))
tmp.replace(path)    # swap in the new file in one step

replace() swaps the file in a single step, so the old ledger stays whole until the new one is ready. sort_keys=True makes the text the same on every run.

Assignment

  1. load_ledger(path) returns the dict stored in the JSON file, or {} if the file doesn't exist yet.

  2. save_ledger(ledger, path) writes json.dumps(ledger, indent=2, sort_keys=True) to a .tmp file next to path, then replaces path with it.

  3. import_folder(folder, path) loads the ledger, reads every .csv in folder (sorted) with csv.DictReader, and for each row:

    • new id: store the row, count it as "added";
    • stored row is different: store the new one, "updated";
    • otherwise: "unchanged".

    Then it saves the ledger and returns {"added": a, "updated": u, "unchanged": n}. Keep rows as the dicts DictReader gives you (all strings).

  4. path can be a string or a Path.