
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 thecsvmodule.
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
- Complete
island_totals(path): read a CSV with the headerisland,item,qtyand return a dict of island to totalqty(as anint). - Complete
write_totals(path, totals): write a CSV with the header rowisland,total, then one row per island sorted by island name.
- Complete
island_totals(path): read a CSV with the headerisland,item,qtyand return a dict of island to totalqty(as anint). - Complete
write_totals(path, totals): write a CSV with the header rowisland,total, then one row per island sorted by island name.
main.py Python sleeping
Press Run to try your code, then Check to test it.