Skip to lesson content
navan✳THE BUILD LABPYTHON 3
0/101 complete
BUILD LAB / PYTHON/ Ship the whole system
EXPERIMENT 99 / 101

From messy rows to a reliable report.

Build a complete import-transform-export pipeline with a rejected-row report.

ADVANCED LAB / BUILD PROJECT
BY NAVAN SAMI◷ 13 MIN READPYTHON 3

01 The idea

This capstone combines a file boundary, validation, typed conversion, and reporting. Valid rows flow into a JSON report; invalid rows are collected with line numbers and reasons instead of being silently ignored. A real import must choose whether partial acceptance is allowed. Here the contract is explicit: export valid records and report rejected records separately.

02 The experiment

Read it once. Predict what will happen. Then copy it into a .py file and run it in your local Python setup.

file_pipeline_project.py
import csv, json
from pathlib import Path
source = Path("incoming.csv")
source.write_text("name,minutes\nBuild,40\nTest,20\nBroken,later\n", encoding="utf-8")
valid, rejected = [], []
with source.open(newline="", encoding="utf-8") as stream:
    reader = csv.DictReader(stream)
    if reader.fieldnames != ["name", "minutes"]:
        raise ValueError("Expected name,minutes headers")
    for line, row in enumerate(reader, start=2):
        try:
            name = row["name"].strip()
            minutes = int(row["minutes"])
            if not name or minutes < 0: raise ValueError("invalid values")
        except (ValueError, AttributeError):
            rejected.append({"line": line, "reason": "Name and nonnegative integer minutes required"})
        else:
            valid.append({"name": name, "minutes": minutes})
report = {"tasks": valid, "total_minutes": sum(row["minutes"] for row in valid), "rejected": rejected}
Path("report.json").write_text(json.dumps(report, indent=2), encoding="utf-8")
print(len(valid), report["total_minutes"], len(rejected))
↳ EXPECTED OUTPUT
2 60 1

03 Under the hood

  1. 1

    The fixture deliberately includes an invalid duration. Header validation catches a wrong input contract before processing rows.

  2. 2

    Each accepted record has a cleaned name and converted integer. The rejected-row report explains the boundary rule without leaking an entire potentially sensitive source row.

  3. 3

    This implementation keeps accepted and rejected records in memory so the exercise stays inspectable. For a very large import, stream results to a staging store or bounded output format and apply an atomic publication strategy.

04 Your turn, builder

A SMALL MISSION

Extract row validation into a reusable function and test negative, nonnumeric, and valid durations.

Reveal one possible solution +
one_possible_solution.py
def validate(row):
    name = row["name"].strip()
    minutes = int(row["minutes"])
    if not name or minutes < 0: raise ValueError("invalid task")
    return {"name": name, "minutes": minutes}
assert validate({"name": " Build ", "minutes": "40"}) == {"name": "Build", "minutes": 40}
for value in ["-1", "later"]:
    try: validate({"name": "Task", "minutes": value})
    except ValueError: pass
    else: raise AssertionError("Invalid duration accepted")
print("Validation checks passed")

↗ Definition of done

  • □Validate the CSV headers.
  • □Accept Build and Test, totaling 60 minutes.
  • □Report the invalid row with a line number and reason.
  • □Write parseable JSON.
  • □Add a CLI input argument and tests for empty and malformed input.

05 Check your signal

QUICK SIGNAL CHECK

Why record rejected rows explicitly?

THAT’S ANOTHER IDEA IN YOUR TOOLKIT.

Experiment. Logged.

When you can explain the idea and make the example your own, mark it complete. Your log stays in this browser.

Keep exploring

Go deeper with the official Python guide ↗.

Built with curiosity. By Navan Sami. ↗Python 3 · Think. Try. Build.