check.py
File: skill-with-scripts/scripts/check.py. Copy it with the button on the code block, or download it as part of the skill-with-scripts template: skill-with-scripts.zip.
#!/usr/bin/env python3"""Validate a CSV file against the required columns. Prints OK or ERROR lines.
Usage: python scripts/check.py <file.csv>Exit codes: 0 = OK, 1 = validation errors, 2 = usage or file problem (wrong arguments,file not found, or not UTF-8 text)."""import csvimport mathimport sysfrom pathlib import Path
# TODO: replace with your real required columns.REQUIRED_COLUMNS = ["id", "name", "amount"]
def check_row(row: dict[str, str], line_no: int) -> list[str]: errors = [] for column in ("id", "name"): if not (row.get(column) or "").strip(): errors.append(f"ERROR: line {line_no}: empty {column}") amount = (row.get("amount") or "").strip() try: if not math.isfinite(float(amount)): errors.append(f"ERROR: line {line_no}: amount '{amount}' is not a finite number") except ValueError: errors.append(f"ERROR: line {line_no}: amount '{amount}' is not a number") return errors
def main() -> int: if len(sys.argv) != 2: print("ERROR: usage: python scripts/check.py <file.csv>") return 2
path = Path(sys.argv[1]) if not path.is_file(): print(f"ERROR: file not found: {path}. Check the path relative to the current directory.") return 2
errors: list[str] = [] rows = 0 try: # utf-8-sig strips the byte-order mark that Excel adds to CSV exports. with path.open(newline="", encoding="utf-8-sig") as fh: reader = csv.DictReader(fh) header = reader.fieldnames or [] missing = [c for c in REQUIRED_COLUMNS if c not in header] if missing: print(f"ERROR: missing columns: {', '.join(missing)}. Found: {', '.join(header) or '(none)'}") return 1
for row in reader: rows += 1 # line_num is the physical line, so it stays right when a quoted field spans lines. errors.extend(check_row(row, reader.line_num)) except UnicodeDecodeError as exc: print(f"ERROR: {path} is not UTF-8 text ({exc.reason} at byte {exc.start}). Re-export it as UTF-8 CSV.") return 2
if errors: print("\n".join(errors)) print(f"{len(errors)} error(s) in {rows} row(s)") return 1
print(f"OK ({rows} rows)") return 0
if __name__ == "__main__": sys.exit(main())