Skip to content

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().

  • 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.csv has the same columns in the order order_date, order_id, store_id, category, product, revenue, quantity.
  • data/config.json: the pipeline config. The script uses input.reports_dir ("data/reports/"), output.dir ("output/"), project, version, and thresholds.min_quantity (1) and thresholds.max_quantity (50).

The six files hold 297 rows and 57,266.39 USD of revenue in total.

Your script must:

  1. Load data/config.json with json.load() and stop with a clear FileNotFoundError if the reports folder in the config does not exist.
  2. Create the output folder from the config with mkdir(parents=True, exist_ok=True).
  3. Find the monthly files with glob("2024-*.csv") and process them in sorted order.
  4. Read each file with csv.DictReader, encoding="utf-8" and newline="". Raise a ValueError if a file has missing or extra columns. Print a note for a file whose columns are only in another order.
  5. Convert quantity to int and revenue to float. Reject a row whose quantity lies outside min_quantity..max_quantity or whose revenue is not positive, and count the rejected rows.
  6. Write output/monthly_summary.csv with one row per month and the columns month, rows, units, revenue (rounded to 2 decimal places) and top_category (the category with the most revenue that month).
  7. Write output/category_summary.json with indent=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.
  8. Prove that the validation works. The real files have no bad rows, so write a small fixture CSV to output/validation_fixture.csv with one good row and three bad ones (quantity 0, quantity 51, revenue -5.00). Assert that read_report() keeps 1 row and rejects 3, and print the result.
  9. Print the run report below, exactly.
  10. End with at least two assert checks that read the output files back.

The expected run report:

Expected output
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 ok
Rows kept: 297, rejected: 0
Total revenue: 57,266.39 USD
Best month: 2024-01 (14,162.33 USD)
Top category: Electronics (32,149.23 USD)
Validation self-test: 3 of 4 fixture rows rejected
Wrote output/monthly_summary.csv and output/category_summary.json
  1. Create the file. Make monthly_report.py in your project folder, next to data/. Add a comment at the top that says what the script reads and writes.

  2. Load the config. Write a function load_config(path) that opens the file with encoding="utf-8", calls json.load() and checks that Path(config["input"]["reports_dir"]).is_dir(). Run the script and print the config’s project name to test it.

  3. Read one file. Write read_report(path, min_qty, max_qty). Open the file in a with block, create a DictReader, and compare reader.fieldnames with 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.

  4. Validate and convert. Inside the loop, convert quantity and revenue. 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 **row copies every key and value of row; the keys written after it replace the copied values.

  5. 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 and max(..., key=...).

  6. Loop over the folder. In main(), sort the files from glob(), call read_report() for each one, print one line per file and collect the month summaries and the category totals.

  7. Write the CSV. Open output/monthly_summary.csv with mode "w", encoding="utf-8" and newline="". Use DictWriter with fieldnames=list(months[0]).

  8. 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) and write_text().

  9. Test the validation. Write check_validation(out_dir, min_qty, max_qty). It writes the fixture with DictWriter, calls read_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.

  10. 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.

  11. Run it with python monthly_report.py from the project folder. Compare every line with the expected report. Delete output/ and run it again: the result must be the same.

A skeleton to start from:

monthly_report.py (starter)
# monthly_report.py: turn the monthly report folder into summary files.
import csv
import json
from 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()
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
  1. Respect config["output"]["overwrite"]: when it is false, open the output files with mode "x" and print a clear message if they already exist.
  2. Append one JSON Lines record per run to output/runs.jsonl with the file names, the row counts and the total revenue.
  3. Add a third output, output/store_month.csv, with the revenue per store and month (one row per pair).
  4. 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.
  5. Turn the bottom main() call into if __name__ == "__main__": main(), and import read_report() from another script. Module 08 explains why this line matters.

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
# 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 csv
import json
from 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()
Output
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 ok
Rows kept: 297, rejected: 0
Total revenue: 57,266.39 USD
Best month: 2024-01 (14,162.33 USD)
Top category: Electronics (32,149.23 USD)
Validation self-test: 3 of 4 fixture rows rejected
Wrote output/monthly_summary.csv and output/category_summary.json

Run it from the project folder:

Terminal
python monthly_report.py

Look at the two output files from the terminal (on Windows, use type instead of cat):

Terminal
cat output/monthly_summary.csv
head -n 16 output/category_summary.json
Output
month,rows,units,revenue,top_category
2024-01,48,65,14162.33,Electronics
2024-02,48,73,4719.04,Sports
2024-03,47,65,12296.72,Electronics
2024-04,52,75,10879.04,Electronics
2024-05,47,65,6675.86,Electronics
2024-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:

  1. 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.
  2. Header check in two levels. sorted(header) != sorted(REQUIRED) catches missing or extra columns, which name matching cannot fix, so it raises ValueError. header == REQUIRED only decides the note: a different order is harmless with DictReader.
  3. 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.
  4. Summaries. summarize_month() builds one dict per month. setdefault() collects the category totals across all files in one pass.
  5. 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 that read_report() rejects exactly the three bad rows.
  6. Outputs. The CSV uses DictWriter with newline="", so it opens cleanly in Excel. The JSON uses indent=2 and a fixed key order, so two runs give byte-identical files that are easy to compare in a code review.
  7. 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.
  8. Rounding. The CSV shows 8533.4, not 8533.40, because it stores the rounded float. Format with :.2f when 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.