07. Files and data formats — Mini-project
The finance team drops one sales extract per month into data/reports/. Every month, someone opens the files in Excel, copies them together and adds up the numbers by hand. Last month, the April file had its columns in another order, and the report showed April revenue of 75 USD.
Write a script, monthly_report.py, that does this job safely and the same way every time:
- it reads its settings from
data/config.json, not from values typed into the code; - it reads every monthly file by column name, so the column order does not matter;
- it rejects rows that break the quantity rules in the config;
- it writes a monthly summary as CSV (for Excel) and a category summary as JSON (for a dashboard) to
output/; - it prints a short run report with relative paths only.
The project uses every part of module 07: pathlib, with, file modes, encodings, csv.DictReader and csv.DictWriter, json.load and json.dumps, glob() with sorting and an output folder created with mkdir().
Dataset
Section titled “Dataset”data/reports/2024-01.csv…2024-06.csv: six monthly extracts of the sales data, 47 to 55 rows each, UTF-8. Columns:order_id, order_date, store_id, product, category, quantity, revenue. Quirk:2024-04.csvhas the same columns in the orderorder_date, order_id, store_id, category, product, revenue, quantity.data/config.json: the pipeline config. The script usesinput.reports_dir("data/reports/"),output.dir("output/"),project,version, andthresholds.min_quantity(1) andthresholds.max_quantity(50).
The six files hold 297 rows and 57,266.39 USD of revenue in total.
Requirements
Section titled “Requirements”Your script must:
- Load
data/config.jsonwithjson.load()and stop with a clearFileNotFoundErrorif the reports folder in the config does not exist. - Create the output folder from the config with
mkdir(parents=True, exist_ok=True). - Find the monthly files with
glob("2024-*.csv")and process them in sorted order. - Read each file with
csv.DictReader,encoding="utf-8"andnewline="". Raise aValueErrorif a file has missing or extra columns. Print a note for a file whose columns are only in another order. - Convert
quantitytointandrevenuetofloat. Reject a row whose quantity lies outsidemin_quantity..max_quantityor whose revenue is not positive, and count the rejected rows. - Write
output/monthly_summary.csvwith one row per month and the columnsmonth,rows,units,revenue(rounded to 2 decimal places) andtop_category(the category with the most revenue that month). - Write
output/category_summary.jsonwithindent=2: the project name, the source file names, the number of rejected rows and, per category, the units and the revenue, from the highest revenue down. - Prove that the validation works. The real files have no bad rows, so write a small fixture CSV to
output/validation_fixture.csvwith one good row and three bad ones (quantity 0, quantity 51, revenue -5.00). Assert thatread_report()keeps 1 row and rejects 3, and print the result. - Print the run report below, exactly.
- End with at least two
assertchecks that read the output files back.
The expected run report:
Monthly report: sales-pipeline 1.4.0 data/reports/2024-01.csv 48 rows ok data/reports/2024-02.csv 48 rows ok data/reports/2024-03.csv 47 rows ok data/reports/2024-04.csv 52 rows column order differs, read by name data/reports/2024-05.csv 47 rows ok data/reports/2024-06.csv 55 rows okRows kept: 297, rejected: 0Total revenue: 57,266.39 USDBest month: 2024-01 (14,162.33 USD)Top category: Electronics (32,149.23 USD)Validation self-test: 3 of 4 fixture rows rejectedWrote output/monthly_summary.csv and output/category_summary.jsonStep plan
Section titled “Step plan”-
Create the file. Make
monthly_report.pyin your project folder, next todata/. Add a comment at the top that says what the script reads and writes. -
Load the config. Write a function
load_config(path)that opens the file withencoding="utf-8", callsjson.load()and checks thatPath(config["input"]["reports_dir"]).is_dir(). Run the script and print the config’s project name to test it. -
Read one file. Write
read_report(path, min_qty, max_qty). Open the file in awithblock, create aDictReader, and comparereader.fieldnameswith the list of required columns: first as sorted lists (same columns?), then as they are (same order?). Return the valid rows, the number of rejected rows and a note. -
Validate and convert. Inside the loop, convert
quantityandrevenue. Use a chained comparison,min_qty <= quantity <= max_qty, for the range rule. Store the converted values in a new dict:{**row, "quantity": quantity, "revenue": revenue}. Inside a dict literal, dict unpacking**rowcopies every key and value ofrow; the keys written after it replace the copied values. -
Summarize a month. Write
summarize_month(month, rows). Count the rows, add up the units and the revenue, and find the top category with a dict of revenue per category andmax(..., key=...). -
Loop over the folder. In
main(), sort the files fromglob(), callread_report()for each one, print one line per file and collect the month summaries and the category totals. -
Write the CSV. Open
output/monthly_summary.csvwith mode"w",encoding="utf-8"andnewline="". UseDictWriterwithfieldnames=list(months[0]). -
Write the JSON. Sort the categories by revenue, build one dict with the metadata and the categories, and write it with
json.dumps(payload, indent=2)andwrite_text(). -
Test the validation. Write
check_validation(out_dir, min_qty, max_qty). It writes the fixture withDictWriter, callsread_report()on it and asserts the result. A test with known bad input is the only way to see that a rule that never fires on real data still works. -
Print the report and check it. Print the totals with format specs (
:,.2f). Read both files back and assert that they match the totals in memory. -
Run it with
python monthly_report.pyfrom the project folder. Compare every line with the expected report. Deleteoutput/and run it again: the result must be the same.
A skeleton to start from:
# monthly_report.py: turn the monthly report folder into summary files.
import csvimport jsonfrom pathlib import Path
CONFIG_PATH = Path("data/config.json")REQUIRED = ["order_id", "order_date", "store_id", "product", "category", "quantity", "revenue"]
def load_config(path): # TODO: json.load the config; raise FileNotFoundError if the reports folder is missing pass
def read_report(path, min_qty, max_qty): # TODO: DictReader; check the header; convert, validate, keep valid rows # TODO: return rows, rejected, note pass
def summarize_month(month, rows): # TODO: return {"month", "rows", "units", "revenue", "top_category"} pass
def check_validation(out_dir, min_qty, max_qty): # TODO: write output/validation_fixture.csv with 1 good and 3 bad rows # TODO: assert that read_report() keeps 1 row and rejects 3; return the counts pass
def main(): # TODO: load the config, create the output folder, loop over the sorted files # TODO: write monthly_summary.csv and category_summary.json, print the report # TODO: assert that the files agree with the totals pass
main()Rubric
Section titled “Rubric”| Criterion | Points | Full points when |
|---|---|---|
| Runs as a script | 2 | python monthly_report.py runs from the project folder with no error |
| Config-driven | 2 | Folder paths and quantity limits come from config.json, not from literals in the code |
| Safe paths | 2 | Sorted glob(), output created with mkdir(parents=True, exist_ok=True), nothing written into data/, only relative paths printed |
| Reads by column name | 3 | DictReader everywhere; April is read correctly; missing columns raise ValueError |
| Validation | 2 | Quantity and revenue rules applied after type conversion; rejected rows counted; the fixture self-test rejects exactly 3 of 4 rows |
| Correct outputs | 3 | Both files have the required columns and keys; the report equals the expected report |
| File handling | 1 | Every open() has encoding= (text) and sits in a with block; CSV files use newline="" |
| Self-checks | 1 | At least two assert statements that read the output files back |
| Total | 16 | 13 or more: you are ready for module 08 |
Stretch goals
Section titled “Stretch goals”- Respect
config["output"]["overwrite"]: when it isfalse, open the output files with mode"x"and print a clear message if they already exist. - Append one JSON Lines record per run to
output/runs.jsonlwith the file names, the row counts and the total revenue. - Add a third output,
output/store_month.csv, with the revenue per store and month (one row per pair). - Read the encoding of each input from the config (add an
"encoding"key yourself), so the same script can process the Latin-1 supplier file. - Turn the bottom
main()call intoif __name__ == "__main__": main(), and importread_report()from another script. Module 08 explains why this line matters.
Reference solution
Section titled “Reference solution”Try the project yourself first. Then compare your script with this one. Your names and structure can differ; your output must not.
Reference solution
# monthly_report.py: turn the monthly report folder into summary files.# Settings come from data/config.json. Inputs stay in data/; results go to output/.
import csvimport jsonfrom pathlib import Path
CONFIG_PATH = Path("data/config.json")REQUIRED = [ "order_id", "order_date", "store_id", "product", "category", "quantity", "revenue",]
def load_config(path): """Return the config dict and fail fast if the reports folder is missing.""" with open(path, encoding="utf-8") as f: config = json.load(f) reports_dir = Path(config["input"]["reports_dir"]) if not reports_dir.is_dir(): raise FileNotFoundError(f"reports folder not found: {reports_dir.as_posix()}") return config
def read_report(path, min_qty, max_qty): """Return (valid rows, rejected count, note) for one monthly CSV file.""" with open(path, encoding="utf-8", newline="") as f: reader = csv.DictReader(f) header = reader.fieldnames if sorted(header) != sorted(REQUIRED): raise ValueError(f"{path.name}: unexpected columns {header}") note = "ok" if header == REQUIRED else "column order differs, read by name" rows = [] rejected = 0 for row in reader: quantity = int(row["quantity"]) revenue = float(row["revenue"]) if not min_qty <= quantity <= max_qty or revenue <= 0: rejected += 1 continue rows.append({**row, "quantity": quantity, "revenue": revenue}) return rows, rejected, note
def summarize_month(month, rows): """Return one summary row: counts, totals and the top category by revenue.""" by_category = {} for row in rows: category = row["category"] by_category[category] = by_category.get(category, 0) + row["revenue"] return { "month": month, "rows": len(rows), "units": sum(row["quantity"] for row in rows), "revenue": round(sum(row["revenue"] for row in rows), 2), "top_category": max(by_category, key=by_category.get), }
def check_validation(out_dir, min_qty, max_qty): """Write a small fixture with known bad rows and check that they are rejected.""" fixture = out_dir / "validation_fixture.csv" with open(fixture, "w", encoding="utf-8", newline="") as f: writer = csv.DictWriter(f, fieldnames=REQUIRED) writer.writeheader() good = { "order_id": "T1", "order_date": "2024-01-02", "store_id": "TEST", "product": "Test", "category": "Test", "quantity": 1, "revenue": 9.99, } writer.writerow(good) writer.writerow(good | {"order_id": "T2", "quantity": 0}) writer.writerow(good | {"order_id": "T3", "quantity": max_qty + 1}) writer.writerow(good | {"order_id": "T4", "revenue": -5.00}) rows, rejected, _ = read_report(fixture, min_qty, max_qty) assert [row["order_id"] for row in rows] == ["T1"] assert rejected == 3 return rejected, rejected + len(rows)
def main(): config = load_config(CONFIG_PATH) reports_dir = Path(config["input"]["reports_dir"]) out_dir = Path(config["output"]["dir"]) out_dir.mkdir(parents=True, exist_ok=True) min_qty = config["thresholds"]["min_quantity"] max_qty = config["thresholds"]["max_quantity"]
files = sorted(reports_dir.glob("2024-*.csv")) months = [] categories = {} rejected_total = 0 print(f"Monthly report: {config['project']} {config['version']}") for path in files: rows, rejected, note = read_report(path, min_qty, max_qty) rejected_total += rejected print(f" {path.as_posix():26} {len(rows):3} rows {note}") months.append(summarize_month(path.stem, rows)) for row in rows: entry = categories.setdefault(row["category"], {"units": 0, "revenue": 0.0}) entry["units"] += row["quantity"] entry["revenue"] += row["revenue"]
summary_csv = out_dir / "monthly_summary.csv" with open(summary_csv, "w", encoding="utf-8", newline="") as f: writer = csv.DictWriter(f, fieldnames=list(months[0])) writer.writeheader() writer.writerows(months)
ranked = sorted( categories.items(), key=lambda item: item[1]["revenue"], reverse=True ) category_json = out_dir / "category_summary.json" payload = { "project": config["project"], "source_files": [path.name for path in files], "rejected_rows": rejected_total, "categories": { name: {"units": e["units"], "revenue": round(e["revenue"], 2)} for name, e in ranked }, } category_json.write_text(json.dumps(payload, indent=2), encoding="utf-8")
total = round(sum(m["revenue"] for m in months), 2) best = max(months, key=lambda m: m["revenue"]) print(f"Rows kept: {sum(m['rows'] for m in months)}, rejected: {rejected_total}") print(f"Total revenue: {total:,.2f} USD") print(f"Best month: {best['month']} ({best['revenue']:,.2f} USD)") print(f"Top category: {ranked[0][0]} ({ranked[0][1]['revenue']:,.2f} USD)") bad, checked = check_validation(out_dir, min_qty, max_qty) print(f"Validation self-test: {bad} of {checked} fixture rows rejected") print(f"Wrote {summary_csv.as_posix()} and {category_json.as_posix()}")
# Self-checks: the summary file must agree with the totals in memory. with open(summary_csv, encoding="utf-8", newline="") as f: saved = list(csv.DictReader(f)) assert len(saved) == len(files) assert round(sum(float(r["revenue"]) for r in saved), 2) == total assert json.loads(category_json.read_text(encoding="utf-8")) == payload
main()Monthly report: sales-pipeline 1.4.0 data/reports/2024-01.csv 48 rows ok data/reports/2024-02.csv 48 rows ok data/reports/2024-03.csv 47 rows ok data/reports/2024-04.csv 52 rows column order differs, read by name data/reports/2024-05.csv 47 rows ok data/reports/2024-06.csv 55 rows okRows kept: 297, rejected: 0Total revenue: 57,266.39 USDBest month: 2024-01 (14,162.33 USD)Top category: Electronics (32,149.23 USD)Validation self-test: 3 of 4 fixture rows rejectedWrote output/monthly_summary.csv and output/category_summary.jsonRun it from the project folder:
python monthly_report.pyLook at the two output files from the terminal (on Windows, use type instead of cat):
cat output/monthly_summary.csvhead -n 16 output/category_summary.jsonmonth,rows,units,revenue,top_category2024-01,48,65,14162.33,Electronics2024-02,48,73,4719.04,Sports2024-03,47,65,12296.72,Electronics2024-04,52,75,10879.04,Electronics2024-05,47,65,6675.86,Electronics2024-06,55,66,8533.4,Electronics{ "project": "sales-pipeline", "source_files": [ "2024-01.csv", "2024-02.csv", "2024-03.csv", "2024-04.csv", "2024-05.csv", "2024-06.csv" ], "rejected_rows": 0, "categories": { "Electronics": { "units": 76, "revenue": 32149.23 },How it works:
- Config first.
load_config()reads the JSON and checks the reports folder before any work starts. A wrong path fails in the first line of output, not halfway through. - Header check in two levels.
sorted(header) != sorted(REQUIRED)catches missing or extra columns, which name matching cannot fix, so it raisesValueError.header == REQUIREDonly decides the note: a different order is harmless withDictReader. - Convert, then validate. The quantity rule compares an
int, not a string.{**row, "quantity": quantity, "revenue": revenue}keeps all the original fields and replaces two with their converted values. - Summaries.
summarize_month()builds one dict per month.setdefault()collects the category totals across all files in one pass. - Validation self-test.
check_validation()writes one good row and three rows that each break one rule.good | {"quantity": 0}uses the dict merge operator (Python 3.9+): it copies the good row into a new dict and changes one field. The asserts prove thatread_report()rejects exactly the three bad rows. - Outputs. The CSV uses
DictWriterwithnewline="", so it opens cleanly in Excel. The JSON usesindent=2and a fixed key order, so two runs give byte-identical files that are easy to compare in a code review. - Self-checks. The asserts read both files back and compare them with the values in memory. If you break the CSV writer, for example by writing a header per file, the read-back no longer matches and the script stops with an error.
- Rounding. The CSV shows
8533.4, not8533.40, because it stores the rounded float. Format with:.2fwhen you print for people; store plain numbers for tools.
Alternative: pandas does the reading and the summaries in a few lines: pd.concat([pd.read_csv(p).assign(month=p.stem) for p in files]), then groupby("month") and to_csv() (modules 24 and 25). Writing it with the standard library first shows you exactly what those calls do, and the script runs anywhere Python runs, with no extra packages.