
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
-
load_ledger(path)returns the dict stored in the JSON file, or{}if the file doesn't exist yet. -
save_ledger(ledger, path)writesjson.dumps(ledger, indent=2, sort_keys=True)to a.tmpfile next topath, thenreplacespathwith it. -
import_folder(folder, path)loads the ledger, reads every.csvinfolder(sorted) withcsv.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 dictsDictReadergives you (all strings). - new
-
pathcan be a string or aPath.
-
load_ledger(path)returns the dict stored in the JSON file, or{}if the file doesn't exist yet. -
save_ledger(ledger, path)writesjson.dumps(ledger, indent=2, sort_keys=True)to a.tmpfile next topath, thenreplacespathwith it. -
import_folder(folder, path)loads the ledger, reads every.csvinfolder(sorted) withcsv.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 dictsDictReadergives you (all strings). - new
-
pathcan be a string or aPath.
Press Run to try your code, then Check to test it.