Python Project Expense Tracker with CSV
What you will build
- An expense tracker that stores records in a CSV file
- Validation of dates, amounts and categories
- Exact money with
Decimal - Totals by category and by month
- Clear errors (with line numbers) and tests
1. The idea
Record every expense with a date, a category, an amount and an optional note. Keep them in a CSV file you can also open in a spreadsheet (lesson 15.6). Then answer: Where does my money go? How much did I spend each month?
day,category,amount,note
2026-03-01,food,12.50,lunch
2026-03-05,food,8.25,"snacks, drinks"
2. The design
| Piece | Job |
|---|---|
Expense (frozen dataclass, lesson 13.11) |
one record: day, category, amount, note |
make_expense(day_text, category, amount_text, note) |
turn text into an Expense, or raise ValueError with a helpful message |
load(path) |
read the whole file into a list of Expense |
append(path, expense) |
add one row at the end (writing the header for a new file) |
total_by_category, total_by_month |
the summaries |
report(expenses) |
the summaries as text |
Design decisions:
- Validate in one place. All text becomes an
Expenseinmake_expense, whether typed by a user or read from the file. After that, the rest of the program can trust the values. Decimalfor money (lesson 3.5). Amounts are stored with exactly two decimal places. Floating-point numbers can accumulate tiny errors (lesson 3.4).- Frozen dataclass: an expense never changes after creation, and frozen instances compare by value, which helps tests.
- Append, don't rewrite: adding one expense writes one line.
- Report bad lines with their line number, never silently skipping them.
3. The code
expenses.py:
"""Expense tracker that keeps its records in a CSV file."""
import csv
from collections import defaultdict
from dataclasses import dataclass
from datetime import date
from decimal import Decimal, InvalidOperation
from pathlib import Path
FIELDS = ["day", "category", "amount", "note"]
@dataclass(frozen=True)
class Expense:
day: date
category: str
amount: Decimal
note: str = ""
def make_expense(day_text, category, amount_text, note=""):
"""Build an Expense from text, or raise ValueError with a clear message."""
try:
day = date.fromisoformat(day_text.strip())
except ValueError:
raise ValueError(f"'{day_text}' is not a date like 2026-03-15") from None
try:
amount = Decimal(amount_text.strip())
except InvalidOperation:
raise ValueError(f"'{amount_text}' is not an amount") from None
if not amount.is_finite() or amount <= 0:
raise ValueError("the amount must be a positive number")
category = category.strip().lower()
if not category:
raise ValueError("a category is needed")
return Expense(day, category, amount.quantize(Decimal("0.01")), note.strip())
def load(path):
"""Read all expenses; bad rows raise ValueError with the line number."""
path = Path(path)
if not path.exists():
return []
expenses = []
with path.open(newline="", encoding="utf-8") as f:
for number, row in enumerate(csv.DictReader(f), start=2):
try:
expenses.append(make_expense(row["day"], row["category"],
row["amount"], row.get("note") or ""))
except (ValueError, KeyError) as error:
raise ValueError(f"line {number}: {error}") from None
return expenses
def append(path, expense):
"""Add one expense to the end of the file (creating it with a header if new)."""
path = Path(path)
is_new = not path.exists() or path.stat().st_size == 0
with path.open("a", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=FIELDS)
if is_new:
writer.writeheader()
writer.writerow({"day": expense.day.isoformat(), "category": expense.category,
"amount": expense.amount, "note": expense.note})
def total_by_category(expenses):
totals = defaultdict(Decimal)
for e in expenses:
totals[e.category] += e.amount
return dict(sorted(totals.items(), key=lambda item: item[1], reverse=True))
def total_by_month(expenses):
totals = defaultdict(Decimal)
for e in expenses:
totals[e.day.strftime("%Y-%m")] += e.amount
return dict(sorted(totals.items()))
def report(expenses):
if not expenses:
return "no expenses yet"
grand = sum(e.amount for e in expenses)
lines = [f"{len(expenses)} expenses, total {grand:,.2f}", "", "By category:"]
for category, amount in total_by_category(expenses).items():
lines.append(f" {category:<12}{amount:>10,.2f} {amount / grand:>4.0%}")
lines += ["", "By month:"]
for month, amount in total_by_month(expenses).items():
lines.append(f" {month} {amount:>10,.2f}")
return "\n".join(lines)
Notes on the code:
date.fromisoformataccepts only real dates like2026-03-15(lesson 17.1);2026-13-01raisesValueError.Decimal("abc")raisesdecimal.InvalidOperation, which the function turns into a plainValueError. The checkis_finite()also rejectsNaNand infinity, whichDecimalwould otherwise accept.quantize(Decimal("0.01"))rounds to two decimal places, so3is stored as3.00.newline=""is used for CSV files in both directions (lesson 15.6).defaultdict(Decimal)starts every total atDecimal()which is zero (lesson 17.3).- Sorting totals by value with
key=lambda item: item[1]puts the biggest category first (lesson 9.6). row.get("note") or ""handles a missing or empty note.enumerate(..., start=2)numbers the lines the way an editor does: line 1 is the header.- The report uses format specs:
,for thousands separators,.2f, and.0%for percentages (lesson 4.6).
Quick check: why are amounts `Decimal` and not `float`?
Decimals add up exactly, as in a ledger; floats store binary approximations (0.1 + 0.2 is not exactly 0.3).
4. A demo run
The script feeds ten entries (four of them wrong) to make_expense and append, prints the file, then the report, in a temporary folder:
import tempfile
from pathlib import Path
from expenses import append, load, make_expense, report, total_by_category
with tempfile.TemporaryDirectory() as folder:
path = Path(folder) / "expenses.csv"
entries = [
("2026-03-01", "Food", "12.50", "lunch"),
("2026-03-02", "transport", "3", ""),
("2026-03-05", "food", "8.25", "snacks, drinks"),
("2026-03-09", "Rent", "400", ""),
("2026-04-01", "food", "20.10", "weekly shop"),
("2026-04-03", "fun", "15", 'cinema "late" show'),
("2026-13-01", "food", "5", ""),
("2026-04-04", "food", "abc", ""),
("2026-04-04", "food", "-4", ""),
("2026-04-04", " ", "4", ""),
]
for day, category, amount, note in entries:
try:
append(path, make_expense(day, category, amount, note))
except ValueError as error:
print("rejected:", error)
print("--- the file")
print(path.read_text(encoding="utf-8"), end="")
expenses = load(path)
print("--- report")
print(report(expenses))
print(total_by_category(expenses)["food"])
Output:
rejected: '2026-13-01' is not a date like 2026-03-15
rejected: 'abc' is not an amount
rejected: the amount must be a positive number
rejected: a category is needed
--- the file
day,category,amount,note
2026-03-01,food,12.50,lunch
2026-03-02,transport,3.00,
2026-03-05,food,8.25,"snacks, drinks"
2026-03-09,rent,400.00,
2026-04-01,food,20.10,weekly shop
2026-04-03,fun,15.00,"cinema ""late"" show"
--- report
6 expenses, total 458.85
By category:
rent 400.00 87%
food 40.85 9%
fun 15.00 3%
transport 3.00 1%
By month:
2026-03 423.75
2026-04 35.10
40.85
What to notice:
- The four bad entries were rejected with clear messages and never reached the file.
- Categories are normalised to lower case (
Foodandfoodare one category;Rentbecamerent). - The CSV module quoted the note containing a comma and doubled the quotes inside
cinema "late" showautomatically. - The percentages (87, 9, 3, 1) add up to 100 here; with rounding they sometimes do not.
A damaged file is reported with the line number:
path.write_text("day,category,amount,note\n2026-03-01,food,12.50,lunch\nnot-a-date,food,1,\n", encoding="utf-8")
load(path)
ValueError: line 3: 'not-a-date' is not a date like 2026-03-15
5. Tests
test_expenses.py covers normalisation, rejection, a file round trip, exact arithmetic, and error reporting:
import tempfile
import unittest
from datetime import date
from decimal import Decimal
from pathlib import Path
from expenses import (append, load, make_expense, report, total_by_category,
total_by_month)
class TestMakeExpense(unittest.TestCase):
def test_normalises_text(self):
e = make_expense(" 2026-03-01 ", " Food ", " 12.5 ", " lunch ")
self.assertEqual((e.day, e.category, e.amount, e.note),
(date(2026, 3, 1), "food", Decimal("12.50"), "lunch"))
def test_rejects_bad_input(self):
bad = [("2026-13-01", "a", "1"), ("2026-01-01", "a", "x"),
("2026-01-01", "a", "0"), ("2026-01-01", "a", "-3"),
("2026-01-01", "a", "NaN"), ("2026-01-01", " ", "1")]
for day, category, amount in bad:
with self.subTest(day=day, category=category, amount=amount):
with self.assertRaises(ValueError):
make_expense(day, category, amount)
class TestFileAndTotals(unittest.TestCase):
def setUp(self):
self.folder = tempfile.TemporaryDirectory()
self.path = Path(self.folder.name) / "e.csv"
def tearDown(self):
self.folder.cleanup()
def test_missing_file_is_empty(self):
self.assertEqual(load(self.path), [])
def test_round_trip_with_commas_and_quotes(self):
original = make_expense("2026-03-05", "food", "8.25", 'snacks, "drinks"')
append(self.path, original)
append(self.path, make_expense("2026-03-06", "fun", "1", ""))
self.assertEqual(load(self.path)[0], original)
self.assertEqual(self.path.read_text(encoding="utf-8").count("day,category"), 1)
def test_totals_are_exact(self):
items = [make_expense("2026-03-01", "a", "0.10"), make_expense("2026-03-02", "a", "0.20"),
make_expense("2026-04-01", "b", "5")]
self.assertEqual(total_by_category(items)["a"], Decimal("0.30"))
self.assertEqual(list(total_by_month(items)), ["2026-03", "2026-04"])
def test_bad_line_is_reported_with_number(self):
self.path.write_text("day,category,amount,note\nx,food,1,\n", encoding="utf-8")
with self.assertRaisesRegex(ValueError, "line 2"):
load(self.path)
def test_report_for_nothing(self):
self.assertEqual(report([]), "no expenses yet")
if __name__ == "__main__":
unittest.main()
Result: Ran 7 tests ... OK. The NaN case shows why is_finite() is needed: Decimal("NaN") is a valid decimal that would slip past a simple <= 0 test (comparison with NaN raises or misbehaves). The 0.10 + 0.20 == 0.30 test passes exactly with Decimal.
6. Ideas to extend it
- A command line with
argparse(lesson 17.8):python expenses.py add 2026-03-01 food 12.50 lunch,python expenses.py report --month 2026-03. - Budgets: a monthly limit per category; warn when exceeded.
- Filters: by category, by date range, by amount.
- Export the report to CSV or JSON (lessons 15.6 and 15.7).
- Currency symbol chosen by the user for display (the file stays plain numbers).
- Charts with a plotting library, or a text bar chart (
"#" * int(amount / 10)). - SQLite storage (lesson 17.10) for fast queries over years of data.
- Undo the last entry (rewrite the file without the last line, using a temporary file, lesson 15.2).
Worked example: what each lesson contributed
| Need | Tool | Lesson |
|---|---|---|
| a record type | frozen dataclass | 13.11 |
| exact money | Decimal, quantize |
3.5 |
| dates | date.fromisoformat, strftime |
17.1 |
| a tabular file | csv.DictReader and DictWriter |
15.6 |
| paths and existence tests | pathlib.Path |
15.4 |
| grouping and summing | defaultdict(Decimal) |
17.3 |
| sorting a dictionary by value | sorted(..., key=...) |
9.6 |
| clear failures | raise ValueError(...) from None |
14.4 and 14.7 |
| trustworthy behaviour | unittest with temporary files |
18.2 |
The central idea: convert and validate at the edge (make_expense), keep exact values inside (Decimal), and check everything with tests. The sample expenses are made up, and no real money or accounts are involved.
Common mistakes
- Using
floatfor money. - Skipping bad rows silently, hiding data problems.
- Forgetting
newline=""when usingcsv. - Rewriting the whole file to add one row.
- Mixing text and numbers in totals (
"12.50" + "3"joins strings). - Accepting
NaNor negative amounts. - Letting categories differ only by capital letters or spaces.
- No header handling, so the first row is treated as data.
Key takeaways
- Convert and validate input once, near the edge, into a trustworthy record type.
- Use
Decimalfor money and ISO dates for storage; use thecsvmodule for files. - Append for adding, report errors with line numbers, and never skip bad data silently.
defaultdictandsortedmake summaries short; format numbers with,,.2fand%.- Tests with temporary files protect the whole pipeline.
Practice
1. What does Decimal("3").quantize(Decimal("0.01")) give?
Show answer
Decimal('3.00').
2. Why does load use start=2 in enumerate?
Show answer
Line 1 of the file is the header, so the first data row is line 2, matching what a text editor shows.
3. How would you add a --month filter to the report?
Show answer
Filter first: [e for e in expenses if e.day.strftime("%Y-%m") == month], then pass the shorter list to report.
4. Why is a negative amount rejected rather than treated as a refund?
Show answer
It is a design choice: a negative number is more often a typing slip. Refunds could be modelled separately (a different type or category) if needed.
5. What would break if Expense were not frozen but was used in a set?
Show answer
A non-frozen dataclass with __eq__ is unhashable, so it could not be put in a set or used as a dictionary key.
6. How do you compute the average spent per month from total_by_month(expenses)?
Show answer
sum(totals.values()) / len(totals) (a Decimal divided by an integer gives a Decimal).