Home / Python / Example programs / Files and data

Python program: Read a CSV file and total a column

Read a CSV of sales and total them per product.

The code

import csv
from collections import defaultdict

with open("sales.csv", "w", encoding="utf-8") as f:
    f.write("date,product,amount\n2026-11-01,tea,12.50\n2026-11-01,cake,8.00\n2026-11-02,tea,9.75\n2026-11-02,coffee,15.20\n")

totals = defaultdict(float)
with open("sales.csv", newline="", encoding="utf-8") as f:
    for row in csv.DictReader(f):
        totals[row["product"]] += float(row["amount"])

for product, total in sorted(totals.items()):
    print(f"{product:<8}${total:>7.2f}")
print(f"{'TOTAL':<8}${sum(totals.values()):>7.2f}")

Output

cake    $   8.00
coffee  $  15.20
tea     $  22.25
TOTAL   $  45.45

How it works

csv.DictReader gives each row as a dictionary keyed by the header. Values are strings, so convert amounts with float. In pandas this is df.groupby("product")["amount"].sum().

Python features used

Learn the ideas behind it in the free lesson Files.