Python for beginners · Lesson 15 of 15
Project: an expense tracker
Put the whole course together: read expenses from a text file, total them per category with a dictionary and print a neat report.
Time to combine everything you have learned into one real program. You will build an expense tracker: it reads a list of expenses from a text file, adds them up per category and prints a report like a bank statement. Along the way you will use files, strings, lists, dictionaries, loops, functions and error handling.
The file expenses.txt has a header line, then one expense per line: the date, a category and the amount, separated by commas. We build the program in small steps and run each one before moving on, which is how programmers work too.
Step 1: read the lines
Read all lines with readlines() and skip the header with a slice: lines[1:] is every line except the first.
with open("expenses.txt", encoding="utf-8") as f:
lines = f.readlines()
rows = lines[1:]
print(len(rows), "expenses")
print(rows[0].strip())
print(rows[-1].strip())8 expenses 2026-11-01,food,12.50 2026-11-09,fun,9.99
Step 2: turn one line into values
A small function takes one line and returns a tuple with the date, the category and the amount as a float. Testing it on its own first makes mistakes easy to spot.
def parse_line(line):
date, category, amount = line.strip().split(",")
return date, category, float(amount)
print(parse_line("2026-11-01,food,12.50\n"))('2026-11-01', 'food', 12.5)Step 3: totals per category
This is the counting pattern from Dictionaries: look things up by name, but instead of adding 1 we add the amount. :.2f shows each total with two decimals.
def parse_line(line):
date, category, amount = line.strip().split(",")
return date, category, float(amount)
with open("expenses.txt", encoding="utf-8") as f:
lines = f.readlines()
totals = {}
for line in lines[1:]:
date, category, amount = parse_line(line)
totals[category] = totals.get(category, 0) + amount
for category, total in totals.items():
print(f"{category}: {total:.2f}")food: 44.35 transport: 4.80 fun: 24.99 bills: 60.00
Step 4: the full program
Real files are messy. This version skips empty lines, counts lines it cannot read instead of crashing, sorts the categories alphabetically, finds the biggest one, and saves the report to report.txt as well. One new trick lines up the columns: in an f-string, {category:<12} keeps the text on the left and adds spaces after it up to 12 characters, and {amount:>10.2f} pushes the number to the right of a 10-character space.
def parse_line(line):
date, category, amount = line.strip().split(",")
return date, category, float(amount)
def read_expenses(filename):
expenses = []
skipped = 0
with open(filename, encoding="utf-8") as f:
lines = f.readlines()
for line in lines[1:]:
if line.strip() == "":
continue
try:
expenses.append(parse_line(line))
except ValueError:
skipped += 1
return expenses, skipped
def totals_by_category(expenses):
totals = {}
for date, category, amount in expenses:
totals[category] = totals.get(category, 0) + amount
return totals
def make_report(totals, skipped):
report = ["EXPENSE REPORT", "-" * 22]
grand_total = 0
biggest = ""
for category in sorted(totals):
amount = totals[category]
report.append(f"{category:<12}{amount:>10.2f}")
grand_total += amount
if biggest == "" or amount > totals[biggest]:
biggest = category
report.append("-" * 22)
report.append(f"{'TOTAL':<12}{grand_total:>10.2f}")
report.append(f"Biggest category: {biggest}")
if skipped > 0:
report.append(f"Skipped {skipped} bad line(s)")
return report
expenses, skipped = read_expenses("expenses.txt")
totals = totals_by_category(expenses)
report = make_report(totals, skipped)
for line in report:
print(line)
with open("report.txt", "w", encoding="utf-8") as out:
for line in report:
out.write(line + "\n")
print("Saved report.txt")EXPENSE REPORT ---------------------- bills 60.00 food 44.35 fun 24.99 transport 4.80 ---------------------- TOTAL 134.14 Biggest category: bills Skipped 1 bad line(s) Saved report.txt
This file has an empty line and a line with abc as the amount: the first is skipped quietly, the second is counted.
Ideas to go further
- Ask the user for a month with
input()and only count expenses whose date starts with it (str.startswith()). - Show each category's share of the total as a percentage.
- Let the user add a new expense and append it to the file with mode
"a".
✎ Exercise
Using the same kind of file, count how many expenses there are in each category and print the counts in alphabetical order, one line each like food: 3 expense(s). Then print Average expense: followed by the average with 2 decimals.
Hint: Use counts.get(category, 0) + 1 to count, add float(amount) to total, and divide by the number of rows at the end.
counts = {}
total = 0
# your code here
Expected output:
food: 3 expense(s) transport: 1 expense(s) Average expense: 7.16
Show a solution
counts = {}
total = 0
with open("expenses.txt", encoding="utf-8") as f:
lines = f.readlines()
rows = lines[1:]
for line in rows:
date, category, amount = line.strip().split(",")
counts[category] = counts.get(category, 0) + 1
total += float(amount)
for category in sorted(counts):
print(f"{category}: {counts[category]} expense(s)")
print(f"Average expense: {total / len(rows):.2f}")food: 3 expense(s) transport: 1 expense(s) Average expense: 7.16
Check yourself
1. Why does the program use lines[1:]?
The first line holds the column names, not an expense. The slice starts at index 1.
2. Which data type is best for keeping a running total per category?
A dictionary maps each category (the key) to its total (the value).
3. What happens to the line 2026-11-07,food,abc?
float("abc") raises a ValueError, which read_expenses catches and counts in skipped.