Stop 06 · Files, Errors & ModulesProjects · 1/1

Expense Tracker with CSV Storage

Part of the Python Roadmap

In short

This project ties the whole phase together: files that remember data, errors handled gracefully, and code split into modules. By the end you'll have a tool that actually tracks where your money goes.

A command-line expense tracker that saves each expense (date, category, amount in rupees, note) to a CSV file and shows totals by category. It practises files, error handling and modules together.

The jaadu writes in a lined household expense register beside a small pile of shop receipts and a few coins on the table.

Think of it like this

Your mom's kharcha register

Many Indian homes keep a notebook where every expense is written down: date, what it was for, how much. At month end you add up each category to see where the money went. Your program is that register, except it never loses a page and does the adding for you.

Watch it happen

Adding one expense

You
main.py
storage.py
expenses.csv

food, 250, lunch

1/5You choose 'Add' and type the category, amount and note.

The big ideas

What you need to know

CSV as a tiny database

One row per expense with columns date, category, amount, note. Excel and Google Sheets can open it too.

Split the code

storage.py reads and writes the file. main.py handles the menu. Each file has one job.

Expect bad input

Catch ValueError for amounts like 'two hundred' and handle a missing file on the first run.

Summaries

Loop over rows and total amounts per category with a dict to see where money goes.

How it works

Build it step by step

  1. 1

    Storage

    Write add_expense and load_expenses using csv.DictWriter and csv.DictReader.

  2. 2

    First run

    Write the header row only if the file doesn't exist yet.

  3. 3

    Input

    Ask for category, amount and note. Retry on a bad amount.

  4. 4

    Summary

    Total each category with a dict and print it sorted by amount.

  5. 5

    Menu

    Tie it together with a while loop and the __main__ guard.

See it in code

Walk through the code

python
1# storage.py2import csv3from datetime import date4from pathlib import Path5 6FILE = Path(__file__).parent / "expenses.csv"7FIELDS = ["date", "category", "amount", "note"]8 9def add_expense(category: str, amount: float, note: str) -> None:10    is_new = not FILE.exists()11    with open(FILE, "a", newline="", encoding="utf-8") as f:12        writer = csv.DictWriter(f, fieldnames=FIELDS)13        if is_new:14            writer.writeheader()15        writer.writerow({"date": date.today().isoformat(), "category": category,16                         "amount": amount, "note": note})17 18def totals_by_category() -> dict[str, float]:19    totals: dict[str, float] = {}20    if not FILE.exists():21        return totals22    with open(FILE, newline="", encoding="utf-8") as f:23        for row in csv.DictReader(f):24            cat = row["category"]25            totals[cat] = totals.get(cat, 0) + float(row["amount"])26    return totals27 28# main.py29from storage import add_expense, totals_by_category30 31def ask_amount() -> float:32    while True:33        try:34            amount = float(input("Amount (Rs): "))35            if amount > 0:36                return amount37            print("Amount must be more than zero.")38        except ValueError:39            print("Please type a number, like 250 or 99.5")40 41if __name__ == "__main__":42    add_expense(input("Category: ").strip().lower(), ask_amount(), input("Note: "))43    for cat, total in sorted(totals_by_category().items(), key=lambda kv: -kv[1]):44        print(f"{cat:<12} Rs {total:,.2f}")

1/7The CSV lives next to the code, with fixed column names.

The core of the tracker: a storage module for the CSV and a main script that validates input and prints totals.

Save yourself the pain

Common mistakes

Oops

Forgetting newline='' when opening CSV files, and getting blank lines between rows on Windows.

Do this instead

Always open CSV files with newline='' as the csv docs recommend.

Oops

Adding amounts straight from the CSV and getting '250' + '120' = '250120'.

Do this instead

Everything read from CSV is a string. Convert with float() before adding.

Your mission

Finish your tracker

~60 min

Quick check

Why does add_expense check FILE.exists() before opening the file?

Go deeper

  1. 1Split the code into storage.py for file work and main.py for the menu.
  2. 2Handle bad amounts and a missing CSV file without crashing.
  3. 3Add a monthly summary that groups spending by category.

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge