Intermediate · Data & Files · Packages: standard library only
Project 14: CSV Report Generator
Creates a sales CSV file, reads it back with csv.DictReader, totals sales by region, product and month with shares, and writes a summary report CSV.
What you will learn
- Write and read CSV files with the csv module
- Convert text columns to numbers
- Group and total data with defaultdict
- Format money and percentages in f-strings
- Create output files in the current folder
Prerequisites
- Lists and dictionaries
- Functions
- File handling and the with statement
- String formatting
- Modules and imports
Packages and installation
Packages: standard library only.
Project structure
csv_report/
main.pyStep-by-step build
- Create sample data. make_sample() writes a header row and eight sales rows with csv.writer. newline='' avoids blank lines on Windows.
- Read the rows. csv.DictReader gives each row as a dictionary keyed by the header names.
- Convert and add columns. Everything from CSV is text, so convert units to int and price to float, then add total and month columns.
- Group the totals. group_total() adds each row's total into a defaultdict keyed by any column name.
- Print tables. print_table() sorts largest first and shows each share of the grand total.
- Write the report. write_report() saves one line per region to report.csv.
- Run and inspect. Open sales.csv and report.csv in a spreadsheet to see the files you made.
Complete source code
"""CSV Report Generator - writes a sales CSV, reads it back and builds a report."""
import csv
from collections import defaultdict
from pathlib import Path
SOURCE = Path("sales.csv")
REPORT = Path("report.csv")
SAMPLE = [
("2024-01-05", "North", "Laptop", 3, 800.00),
("2024-01-09", "South", "Phone", 10, 300.00),
("2024-01-15", "North", "Phone", 4, 300.00),
("2024-02-02", "East", "Laptop", 2, 800.00),
("2024-02-11", "South", "Tablet", 6, 250.50),
("2024-02-20", "East", "Phone", 7, 300.00),
("2024-03-03", "North", "Tablet", 5, 250.50),
("2024-03-14", "South", "Laptop", 1, 800.00),
]
def make_sample():
"""Create the input file so the demo works offline."""
with SOURCE.open("w", newline="", encoding="utf-8") as f:
writer = csv.writer(f)
writer.writerow(["date", "region", "product", "units", "price"])
writer.writerows(SAMPLE)
def read_sales():
"""Read rows as dictionaries and convert numbers."""
with SOURCE.open(newline="", encoding="utf-8") as f:
rows = list(csv.DictReader(f))
for row in rows:
row["units"] = int(row["units"])
row["price"] = float(row["price"])
row["total"] = row["units"] * row["price"]
row["month"] = row["date"][:7]
return rows
def group_total(rows, key):
"""Sum the 'total' column for every value of `key`."""
sums = defaultdict(float)
for row in rows:
sums[row[key]] += row["total"]
return dict(sums)
def print_table(title, sums):
print(f"\n{title}")
grand = sum(sums.values())
for name, value in sorted(sums.items(), key=lambda kv: -kv[1]):
print(f" {name:<8}{value:>10,.2f} {value / grand:>6.1%}")
def write_report(rows):
"""Save a summary CSV with one line per region."""
sums = group_total(rows, "region")
with REPORT.open("w", newline="", encoding="utf-8") as f:
writer = csv.writer(f)
writer.writerow(["region", "total"])
for name in sorted(sums):
writer.writerow([name, f"{sums[name]:.2f}"])
def main():
make_sample()
rows = read_sales()
print(f"Read {len(rows)} rows from {SOURCE}")
print_table("Sales by region", group_total(rows, "region"))
print_table("Sales by product", group_total(rows, "product"))
print_table("Sales by month", group_total(rows, "month"))
write_report(rows)
print(f"\nWrote {REPORT}:")
print(REPORT.read_text(encoding="utf-8").strip())
if __name__ == "__main__":
main()
Code explanation
csv.writer and DictReader
The writer turns lists into CSV lines; DictReader turns lines into dictionaries, so you use row['units'] instead of row[3].
Type conversion
CSV has no types. int() and float() must be applied after reading, otherwise '3' * '800.0' fails.
defaultdict(float)
A missing key starts at 0.0, so sums[key] += value works without checking if the key exists.
Reusable grouping
Because group_total takes the key name as a parameter, the same function produces region, product and month reports.
Format specs
{value:>10,.2f} right-aligns, adds thousands commas and keeps two decimals; {share:>6.1%} shows a percentage.
Expected output
Read 8 rows from sales.csv
Sales by region
South 5,303.00 38.3%
North 4,852.50 35.0%
East 3,700.00 26.7%
Sales by product
Phone 6,300.00 45.5%
Laptop 4,800.00 34.6%
Tablet 2,755.50 19.9%
Sales by month
2024-01 6,600.00 47.6%
2024-02 5,203.00 37.6%
2024-03 2,052.50 14.8%
Wrote report.csv:
region,total
East,3700.00
North,4852.50
South,5303.00Common errors and solutions
Solution: The header names in the file do not match the code. Check spelling and case of the first row.
Solution: A cell is empty or has text. Clean the data or wrap the conversion in try/except and skip bad rows.
Solution: Open the file with newline='' when using the csv module.
Solution: The file uses another encoding. Pass encoding='utf-8' or the correct one when opening.
Ideas to improve the project
- Accept the input file name with argparse
- Skip and report invalid rows
- Add a date range filter
- Write a report for each grouping
- Show the best-selling product per region
- Output an HTML table