Python Essentials · 30 min · 180 XP
Guided lab: sales report
Read a CSV file, total it up, and write a report, like a script you'd actually run on Monday morning.
This is where Python pays for itself: a task you'd otherwise do by hand every week, done in a few seconds. Most of these tasks have the same shape. Read a file, clean and total the data, and write the result somewhere.
Open files with with, which closes them for you even if an error happens halfway through. Pass encoding="utf-8" so accented names survive, and for CSV files also pass newline="" (the csv module handles line endings itself).
import csv
from decimal import Decimal
with open("sales.csv", encoding="utf-8", newline="") as f:
for row in csv.DictReader(f): # each row is a dict keyed by the header
amount = Decimal(row["amount"]) # exact decimal money
print(row["category"], amount)
with open("summary.csv", "w", encoding="utf-8", newline="") as f:
writer = csv.writer(f)
writer.writerow(["category", "total"])
writer.writerow(["Gear", "55.00"])Real files are messy. Validate the header once, then validate each row. A row may have n/a, a blank category or a non-finite number. Skip bad rows and say so by counting them rather than crashing on row 3,000 or quietly treating bad data as zero. For money, use Decimal from the original CSV text; converting through float first can carry binary rounding error into the result.
Use the local-workflow lesson to save this as report.py, pass real input and output paths, and run it in a terminal. The challenge runs in the browser's small temporary file system, so open() works here too; its files disappear when the page is reset.
Loading your workspace…