Code

Merge the Weekly Ledgers

Every week the lighthouse keepers send a CSV ledger. Merging them by hand means a lot of copy and paste. Python does it in a few lines.

import csv
from pathlib import Path

rows = []
for path in sorted(Path("ledgers").glob("*.csv")):
    with open(path, newline="") as f:
        for row in csv.DictReader(f):
            rows.append(row)
  • sorted(...) makes week1.csv come before week2.csv every time.
  • csv.DictReader turns each line into a dict, using the header row as keys: {"id": "A1", "item": "oil", "qty": "3"}. Every value is a string.
  • newline="" is what the csv docs ask for. It stops stray blank lines on Windows.

Writing works the same way in reverse:

with open("merged.csv", "w", newline="") as f:
    writer = csv.DictWriter(f, fieldnames=["id", "item"])
    writer.writeheader()
    writer.writerows(rows)

The csv module also handles tricky values, like an item called rope, long that contains a comma.

Save the merged file outside the input folder. Otherwise the next run would merge the merged file too!

Assignment

  1. merge_ledgers(folder) returns one list with the rows (dicts) of every .csv file in folder: files in sorted name order, rows in file order. Skip anything that isn't a file.
  2. Add a "source" key to each row with its file's name (like "week1.csv"), so every row can be traced back.
  3. write_csv(rows, path) writes the rows to path with a header. Use the keys of the first row as the columns. You may assume rows isn't empty.