Project: a command-line expense tracker
Combine files, errors, classes, JSON, CSV and dates into a real expense tracker that saves its data and exports to Excel.
In this lesson you will
- Plan a program as small functions
- Save and load data with JSON
- Validate input with try/except
- Export to CSV and extend the project
About 30 minutes
Your first real application
Time to put everything together. Over the last ten lessons you learned files, errors, modules, classes, JSON, dates and comprehensions. Now you will build a command-line expense tracker: it lets you add expenses, lists them, shows totals by category, and remembers everything between runs by saving to a JSON file. It is small enough to finish today and real enough to use.
What we are building
- Add an expense: amount, category, note, with today’s date.
- List all expenses, newest first.
- Show a total for each category.
- Export everything to a CSV file for Excel.
- Save automatically to a JSON file so nothing is lost.
Step 1: plan the data
Each expense is a small record. A dataclass fits well. All expenses go in a list, and the list is saved as JSON.
from dataclasses import dataclass, asdict
from datetime import date
@dataclass
class Expense:
amount: float
category: str
note: str
day: str # stored as text like 2026-03-15
e = Expense(450.0, "food", "Lunch", date(2026, 3, 15).isoformat())
print(e)
print(asdict(e))
Expense(amount=450.0, category='food', note='Lunch', day='2026-03-15')
{'amount': 450.0, 'category': 'food', 'note': 'Lunch', 'day': '2026-03-15'}
Step 2: saving and loading
import json
from pathlib import Path
from dataclasses import dataclass, asdict
@dataclass
class Expense:
amount: float
category: str
note: str
day: str
FILE = Path("expenses.json")
def load():
if not FILE.exists():
return []
try:
raw = json.loads(FILE.read_text(encoding="utf-8"))
except json.JSONDecodeError:
print("Warning: the data file is damaged, starting fresh.")
return []
return [Expense(**item) for item in raw]
def save(expenses):
FILE.write_text(json.dumps([asdict(e) for e in expenses], indent=2), encoding="utf-8")
items = load()
print("Loaded", len(items))
items.append(Expense(450, "food", "Lunch", "2026-03-15"))
save(items)
print("Loaded again:", len(load()))
print(FILE.read_text())
Loaded 0
Loaded again: 1
[
{
"amount": 450,
"category": "food",
"note": "Lunch",
"day": "2026-03-15"
}
]
Notice the care taken: a missing file returns an empty list, and a damaged file is reported instead of crashing the program. Expense(**item) unpacks a dictionary into the constructor’s arguments.
Step 3: the logic
from collections import defaultdict
from dataclasses import dataclass
@dataclass
class Expense:
amount: float
category: str
note: str
day: str
def totals_by_category(expenses):
totals = defaultdict(float)
for e in expenses:
totals[e.category] += e.amount
return dict(sorted(totals.items(), key=lambda kv: kv[1], reverse=True))
def newest_first(expenses):
return sorted(expenses, key=lambda e: e.day, reverse=True)
data = [
Expense(450, "food", "Lunch", "2026-03-15"),
Expense(1200, "transport", "Taxi", "2026-03-16"),
Expense(300, "food", "Snacks", "2026-03-17"),
Expense(2500, "bills", "Internet", "2026-03-01"),
]
print(totals_by_category(data))
for e in newest_first(data)[:2]:
print(e.day, e.note)
{'bills': 2500.0, 'transport': 1200.0, 'food': 750.0}
2026-03-17 Snacks
2026-03-16 Taxi
The logic functions take data in and return results. They do no printing and no input. That separation makes them easy to test and reuse: a good habit for any program.
Step 4: the complete program
"""A command-line expense tracker that remembers its data."""
import csv
import json
from collections import defaultdict
from dataclasses import dataclass, asdict
from datetime import date
from pathlib import Path
FILE = Path("expenses.json")
@dataclass
class Expense:
amount: float
category: str
note: str
day: str
def load():
if not FILE.exists():
return []
try:
raw = json.loads(FILE.read_text(encoding="utf-8"))
except json.JSONDecodeError:
print("Warning: data file damaged, starting fresh.")
return []
return [Expense(**item) for item in raw]
def save(expenses):
FILE.write_text(json.dumps([asdict(e) for e in expenses], indent=2), encoding="utf-8")
def ask_amount():
while True:
text = input("Amount: ")
try:
value = float(text)
except ValueError:
print(" Please type a number.")
continue
if value <= 0:
print(" Amount must be above zero.")
continue
return value
def add_expense(expenses):
amount = ask_amount()
category = input("Category: ").strip().lower() or "other"
note = input("Note: ").strip()
expenses.append(Expense(amount, category, note, date.today().isoformat()))
save(expenses)
print(" Saved.")
def list_expenses(expenses):
if not expenses:
print(" No expenses yet.")
return
for e in sorted(expenses, key=lambda e: e.day, reverse=True):
print(f" {e.day} {e.category:<10} {e.amount:>9.2f} {e.note}")
def show_totals(expenses):
totals = defaultdict(float)
for e in expenses:
totals[e.category] += e.amount
for category, total in sorted(totals.items(), key=lambda kv: kv[1], reverse=True):
print(f" {category:<10} {total:>9.2f}")
print(f" {'TOTAL':<10} {sum(totals.values()):>9.2f}")
def export_csv(expenses, filename="expenses.csv"):
with open(filename, "w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=["day", "category", "amount", "note"])
writer.writeheader()
for e in expenses:
writer.writerow({"day": e.day, "category": e.category, "amount": e.amount, "note": e.note})
print(f" Exported {len(expenses)} rows to {filename}")
MENU = """
1) Add expense
2) List expenses
3) Totals by category
4) Export to CSV
5) Quit"""
def main():
expenses = load()
while True:
print(MENU)
choice = input("Choose: ").strip()
if choice == "1":
add_expense(expenses)
elif choice == "2":
list_expenses(expenses)
elif choice == "3":
show_totals(expenses)
elif choice == "4":
export_csv(expenses)
elif choice == "5":
print("Goodbye!")
break
else:
print(" Please choose 1 to 5.")
if __name__ == "__main__":
main()
import tracker
tracker.main()
1) Add expense
2) List expenses
3) Totals by category
4) Export to CSV
5) Quit
Choose: 1
Amount: abc
Please type a number.
Amount: 450
Category: Food
Note: Lunch
Saved.
1) Add expense
2) List expenses
3) Totals by category
4) Export to CSV
5) Quit
Choose: 1
Amount: 1200
Category: Transport
Note: Taxi
Saved.
1) Add expense
2) List expenses
3) Totals by category
4) Export to CSV
5) Quit
Choose: 1
Amount: 300
Category: food
Note: Snacks
Saved.
1) Add expense
2) List expenses
3) Totals by category
4) Export to CSV
5) Quit
Choose: 2
2026-10-31 food 450.00 Lunch
2026-10-31 transport 1200.00 Taxi
2026-10-31 food 300.00 Snacks
1) Add expense
2) List expenses
3) Totals by category
4) Export to CSV
5) Quit
Choose: 3
transport 1200.00
food 750.00
TOTAL 1950.00
1) Add expense
2) List expenses
3) Totals by category
4) Export to CSV
5) Quit
Choose: 4
Exported 3 rows to expenses.csv
1) Add expense
2) List expenses
3) Totals by category
4) Export to CSV
5) Quit
Choose: 9
Please choose 1 to 5.
1) Add expense
2) List expenses
3) Totals by category
4) Export to CSV
5) Quit
Choose: 5
Goodbye!
The lines above that show your typing (such as 450 after “Amount:”) are the answers fed to input() in this pretend session. When you run the file yourself in a terminal, you type them yourself. Dates in the list are today’s date, so yours will differ from any written example.
Step 5: run it yourself
- Create a folder, for example
expense_tracker, and a filetracker.pyinside it. - Paste in the program above.
- Open a terminal in that folder and run
python tracker.py. - Add a few expenses, quit with 5, run it again, and choose 2. Your data is still there.
- Open the folder: you will find
expenses.json. After choosing 4 you will also findexpenses.csv, which opens in Excel.
How the pieces fit together
| Lesson | Where it appears |
|---|---|
| Files | FILE.read_text, write_text, open for CSV |
| Errors | try/except for bad numbers and damaged files |
| Modules | csv, json, pathlib, datetime, collections |
| Classes | The Expense dataclass |
| JSON and CSV | Saving and exporting |
| Dates | date.today().isoformat() |
| Comprehensions | [asdict(e) for e in expenses] |
| Functions | Each job is one small function |
Ideas to extend it
- Add a delete option that removes an expense by number.
- Filter the list by month using
day.startswith("2026-03"). - Add a monthly budget and warn when it is exceeded.
- Show a bar chart of totals with the
matplotlibpackage. - Move the logic into a class
ExpenseBookand add tests withpytest. - Turn it into a small website with Flask later in the course.
Putting every line inside one giant main(). When a program grows, a long block of code becomes unreadable. Notice how this one is built from small functions, each doing one job with a clear name. Copy that structure.
Add a delete_expense(expenses) function: print the numbered list, ask which number to delete, validate the answer, remove it and save. Describe in a few words how you would test it.
Show one possible answer
def delete_expense(expenses):
for i, e in enumerate(expenses, start=1):
print(f" {i}) {e.day} {e.note} {e.amount}")
text = input("Delete which number? ")
try:
index = int(text) - 1
removed = expenses.pop(index)
except (ValueError, IndexError):
print(" Not a valid number.")
return
save(expenses)
print(" Deleted:", removed.note)
# Test idea: add three fake expenses to a list, call the function with
# input "2", then check the list has two items and that the file was saved.
Write a function monthly_total(expenses, month) that returns the total for a month such as “2026-03”.
Hint: A generator expression with an if at the end.
Show one possible answer
def monthly_total(expenses, month):
return sum(e.amount for e in expenses if e.day.startswith(month))
You can read and write files, handle errors, structure code with functions and classes, and build a tool that saves data. That is the foundation of nearly all software. The advanced course turns this into professional habits: decorators, testing, regular expressions and more.
Check what you learned
Five quick questions. Pick an answer and you will see straight away whether it is right and why.
Why keep logic functions free of print and input?
- They are easier to test and reuse
- They run faster
- Python requires it
- They use less memory
Separating logic from input/output is good design.
How does the tracker remember data between runs?
- It keeps it in RAM
- It saves to a JSON file and loads it at start
- It uses the clipboard
- It does not
load() and save() use expenses.json.
What does Expense(**item) do?
- Multiplies values
- Copies a class
- Deletes an item
- Unpacks a dictionary into constructor arguments
** unpacks dictionary keys as keyword arguments.
What protects the program from a damaged data file?
- A loop
- try/except around json.loads
- A class
- A comment
It catches JSONDecodeError.
Which module writes the Excel-friendly export?
- json
- datetime
- math
- csv
csv.DictWriter writes the rows.
Summary
- Small functions with clear jobs make programs readable.
- load() and save() give a program memory.
- Validate input in loops with try/except.
- Separate logic from input/output.
Questions
Where is my data saved?
In expenses.json in the folder where you run the program.
Can I change the categories?
Yes. They are just text; type any category you like, or add a fixed list and validate against it.
How do I run it every day?
Open a terminal in the folder and run python tracker.py. Later you can create a shortcut or convert it into a web app.
