
Code
Side Quest: One Record at a Time
A patrol log can hold millions of records. Loading it all with one
json.load needs the whole file in memory. Worse, one bad
character ruins everything.
JSON Lines
JSON Lines files (they often end in .jsonl) fix both
problems. Each line is one complete JSON value:
{"night": 1, "island": "Amber Isle", "oil": 4}
{"night": 2, "island": "Fog Reach", "oil": 6}
Read the file line by line, and decode each line on its own with
json.loads:
with open("patrols.jsonl", encoding="utf-8") as f:
for number, line in enumerate(f, start=1):
record = json.loads(line)
Only one line is in memory at a time. If a line is damaged, you can note its line number and carry on with the next one. The good records are still good.
Pip tip: "Line 2 is broken" is a message a human can fix. "Something went wrong" is not.
Assignment
Complete read_records(path). Return a tuple
(records, bad_lines):
- Read the file one line at a time with a
forloop. Number the lines from 1. - Skip blank lines (empty after
.strip()). They are neither records nor bad. - Decode every other line with
json.loads. If the result is a dict, append it torecords. - If a line isn't valid JSON, or it's valid JSON but not a
dict, append its line number to
bad_linesand keep going.
Complete read_records(path). Return a tuple
(records, bad_lines):
- Read the file one line at a time with a
forloop. Number the lines from 1. - Skip blank lines (empty after
.strip()). They are neither records nor bad. - Decode every other line with
json.loads. If the result is a dict, append it torecords. - If a line isn't valid JSON, or it's valid JSON but not a
dict, append its line number to
bad_linesand keep going.
main.py Python sleeping
Press Run to try your code, then Check to test it.