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_num is always the real line in the file.
  • Short rows (a missing comma) give None for the missing columns. row["qty"] or "" turns None into "", which int() then rejects with a normal ValueError.

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.

  1. 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.
  2. Check each row (lines start at 2) in this order:
    • item is blank after .strip(): reason "missing item".
    • qty isn't a whole number, or is below 0: reason "bad qty".
  3. Accepted rows are dicts {"id": ..., "item": ..., "qty": <int>}.
  4. Each note is a dict {"file": <file name>, "line": <int>, "reason": <text>}.