Skip to content

check.py

Source file: 01-skills/templates/skill-with-scripts/scripts/check.py. Copy it from the repository, or use the copy button on the code block.

check.py
#!/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 / file problem.
"""
import csv
import sys
from pathlib import Path
# TODO: replace with your real required columns.
REQUIRED_COLUMNS = ["id", "name", "amount"]
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] = []
with path.open(newline="", encoding="utf-8") 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 line_no, row in enumerate(reader, start=2):
if not (row.get("id") or "").strip():
errors.append(f"ERROR: line {line_no}: empty id")
amount = (row.get("amount") or "").strip()
try:
float(amount)
except ValueError:
errors.append(f"ERROR: line {line_no}: amount '{amount}' is not a number")
if errors:
print("\n".join(errors))
return 1
print("OK")
return 0
if __name__ == "__main__":
sys.exit(main())