Code

The Guild Ledger

CSV (comma-separated values) files are tables in plain text. Every spreadsheet app can open them.

island,item,qty
Amber Isle,"Oil, lamp",3

Why not just line.split(",")? Because a value may itself contain a comma inside quotes, like "Oil, lamp". The csv module handles all of that for you.

import csv

with open("ledger.csv", newline="", encoding="utf-8") as f:
    for row in csv.DictReader(f):     # uses the header row
        print(row["island"], int(row["qty"]))
  • csv.reader(f) gives each row as a list; csv.DictReader(f) gives a dict keyed by the header names.
  • Every value comes back as a string, so convert numbers.
  • Always open CSV files with newline="" so line endings are left to the csv module.

Writing works the same way:

with open("out.csv", "w", newline="", encoding="utf-8") as f:
    writer = csv.writer(f)
    writer.writerow(["island", "total"])
    writer.writerow(["Amber Isle", 7])

Assignment

  1. Complete island_totals(path): read a CSV with the header island,item,qty and return a dict of island to total qty (as an int).
  2. Complete write_totals(path, totals): write a CSV with the header row island,total, then one row per island sorted by island name.