
Side Quest: Account for Every Row
An import that quietly drops rows is a nightmare. Nobody notices the missing deliveries until the lanterns go dark. A trustworthy import accounts for every row. Each row ends up either accepted or rejected with a reason, and the counts must add up:
rows read == accepted + rejected
If they don't, the importer has a bug, and it should say so loudly.
Real line numbers
A rejection is only useful if a human can find the row. Report the line number in the file, where the header is line 1.
There's a trap: csv.DictReader silently skips blank lines. So
counting rows with enumerate(reader, start=2) drifts after a blank
line. The reader knows better: reader.line_num is the number of
lines it has read so far, so right after it hands you a row, that's
the row's real line.
reader = csv.DictReader(io.StringIO(text))
for row in reader:
line = reader.line_num
Short rows get None for their missing fields, so read values with
(row.get("id") or "").strip().
Assignment
-
import_rows(text)returns(accepted, rejected, rows_read). Check each row's rules in this order and reject with the first reason that applies:"missing id":idis blank;"duplicate id": that id was already accepted;"bad litres":litresis missing or not all digits.
A rejected row is
{"row": line, "reason": ...}. An accepted row is{"row": line, "id": ..., "island": ..., "litres": int}, with every text value stripped. -
summary(accepted, rejected, rows_read)returns"Read 6 rows: 2 accepted, 4 rejected". If the counts don't add up, raiseValueErrorinstead.
-
import_rows(text)returns(accepted, rejected, rows_read). Check each row's rules in this order and reject with the first reason that applies:"missing id":idis blank;"duplicate id": that id was already accepted;"bad litres":litresis missing or not all digits.
A rejected row is
{"row": line, "reason": ...}. An accepted row is{"row": line, "id": ..., "island": ..., "litres": int}, with every text value stripped. -
summary(accepted, rejected, rows_read)returns"Read 6 rows: 2 accepted, 4 rejected". If the counts don't add up, raiseValueErrorinstead.
Press Run to try your code, then Check to test it.