
Code
Keep the Reject Reasons
Real data is messy. A careful import doesn't crash on one bad row, and it doesn't quietly drop it either. It sorts rows into two piles:
- accepted: rows that pass every check.
- rejected: a note for each problem, saying which file, which line, and why.
The rejected notes are gold. Someone can fix the source file and run the import again.
for row in reader:
line = reader.line_num # the real line in the file
try:
qty = int(row["qty"] or "")
except ValueError:
rejected.append({"file": path.name,
"line": line, "reason": "bad qty"})
continue
Two traps hide in real files:
- Blank lines are skipped by
csv.DictReader, so counting rows yourself gives the wrong line number.reader.line_numis always the real line in the file. - Short rows (a missing comma) give
Nonefor the missing columns.row["qty"] or ""turnsNoneinto"", whichint()then rejects with a normalValueError.
Checking the header
reader.fieldnames is the header as a list. Compare it as a set,
so the column order doesn't matter:
set(reader.fieldnames) == {"id", "item", "qty"}. An empty file has
no header at all (fieldnames is None), so use
set(reader.fieldnames or []).
Assignment
import_ledgers(folder) returns (accepted, rejected), reading every
.csv file in folder in sorted order.
- If a file's header (as a set) isn't exactly
{"id", "item", "qty"}, reject the whole file with one note:"line": 1,"reason": "bad header". Skip its rows. Empty files count too. - Check each row (lines start at 2) in this order:
itemis blank after.strip(): reason"missing item".qtyisn't a whole number, or is below 0: reason"bad qty".
- Accepted rows are dicts
{"id": ..., "item": ..., "qty": <int>}. - Each note is a dict
{"file": <file name>, "line": <int>, "reason": <text>}.
import_ledgers(folder) returns (accepted, rejected), reading every
.csv file in folder in sorted order.
- If a file's header (as a set) isn't exactly
{"id", "item", "qty"}, reject the whole file with one note:"line": 1,"reason": "bad header". Skip its rows. Empty files count too. - Check each row (lines start at 2) in this order:
itemis blank after.strip(): reason"missing item".qtyisn't a whole number, or is below 0: reason"bad qty".
- Accepted rows are dicts
{"id": ..., "item": ..., "qty": <int>}. - Each note is a dict
{"file": <file name>, "line": <int>, "reason": <text>}.
main.py Python sleeping
Press Run to try your code, then Check to test it.