Expense Tracker Project Examples
Short, runnable programs that show python expense tracker project in action. Read the explanation, press Run, then change the code and try your own ideas. New to the topic? Start with the Python Expense Tracker Project lesson.
1Step 2: load safely on the very first run
The first time the program runs there is no file yet, so open() raises FileNotFoundError. Catching it and returning an empty list lets the tracker start fresh. The demo deletes any old file first so it always behaves like a first run.
import json
import os
def load_expenses(path):
try:
with open(path) as file:
return json.load(file)
except FileNotFoundError:
return []
def save_expenses(expenses, path):
with open(path, "w") as file:
json.dump(expenses, file, indent=2)
if os.path.exists("my_expenses.json"):
os.remove("my_expenses.json") # start fresh, like a first run
expenses = load_expenses("my_expenses.json")
print("First run:", expenses)
expenses.append({"date": "2024-05-04", "category": "books", "amount": 9.99})
save_expenses(expenses, "my_expenses.json")
print("Next run:", load_expenses("my_expenses.json"))Expected outputFirst run: []
Next run: [{'date': '2024-05-04', 'category': 'books', 'amount': 9.99}]
2Extension: totals per month
Dates stored as YYYY-MM-DD text are easy to group: the first seven characters are the year and month. The same running-total pattern then works for months instead of categories.
expenses = [
{"date": "2024-04-28", "category": "food", "amount": 30.00},
{"date": "2024-04-30", "category": "rent", "amount": 650.00},
{"date": "2024-05-02", "category": "food", "amount": 42.50},
{"date": "2024-05-15", "category": "fun", "amount": 25.00},
{"date": "2024-05-20", "category": "food", "amount": 18.25},
]
by_month = {}
for row in expenses:
month = row["date"][:7]
by_month[month] = by_month.get(month, 0) + row["amount"]
for month in sorted(by_month):
print(month, f"{by_month[month]:>8.2f}")Expected output2024-04 680.00
2024-05 85.75
3Extension: a text bar chart report
Percentages make a report easier to read. Repeating "#" once for every 5% draws a simple bar chart using nothing but text.
totals = {"food": 21.25, "fun": 15.00, "transport": 3.20}
grand = sum(totals.values())
for category in sorted(totals, key=totals.get, reverse=True):
share = totals[category] / grand * 100
bar = "#" * round(share / 5)
print(f"{category:<10}{totals[category]:>7.2f}{share:>6.1f}% {bar}")Expected outputfood 21.25 53.9% ###########
fun 15.00 38.0% ########
transport 3.20 8.1% ##
4An interactive version with input()
A menu loop turns the tracker into a small app: each command is read with input() and handled by an if/elif branch. On this page the commands come from the Input box, one per line.
expenses = []
while True:
command = input("add / report / quit: ")
if command == "add":
category = input("Category: ")
amount = float(input("Amount: "))
expenses.append({"category": category, "amount": amount})
elif command == "report":
totals = {}
for row in expenses:
totals[row["category"]] = totals.get(row["category"], 0) + row["amount"]
for category, total in totals.items():
print(f" {category}: {total:.2f}")
elif command == "quit":
break
else:
print("Unknown command:", command)Expected outputadd / report / quit: add
Category: food
Amount: 12.5
add / report / quit: add
Category: bus
Amount: 2.4
add / report / quit: list
Unknown command: list
add / report / quit: add
Category: food
Amount: 7
add / report / quit: report
food: 19.50
bus: 2.40
add / report / quit: quit
Practise next
Python Expense Tracker Project exercises → Back to the lesson
Working with JSON in Python examplesPython CSV Files examplesPandas Basics examplesPython Calculator Project examples