
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(...)makesweek1.csvcome beforeweek2.csvevery time.csv.DictReaderturns 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 thecsvdocs 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
merge_ledgers(folder)returns one list with the rows (dicts) of every.csvfile infolder: files in sorted name order, rows in file order. Skip anything that isn't a file.- Add a
"source"key to each row with its file's name (like"week1.csv"), so every row can be traced back. write_csv(rows, path)writes the rows topathwith a header. Use the keys of the first row as the columns. You may assumerowsisn't empty.
merge_ledgers(folder)returns one list with the rows (dicts) of every.csvfile infolder: files in sorted name order, rows in file order. Skip anything that isn't a file.- Add a
"source"key to each row with its file's name (like"week1.csv"), so every row can be traced back. write_csv(rows, path)writes the rows topathwith a header. Use the keys of the first row as the columns. You may assumerowsisn't empty.
main.py Python sleeping
Press Run to try your code, then Check to test it.