Personal Expense Tracker with File Handling
IntermediateBuild a personal finance management tool with Python
1) Project Overview
The Personal Expense Tracker helps users record, view, and manage their daily expenses.
It allows the user to add, view, and analyze expenses saved in a local text file.
This project simulates how real-world expense tracking or budgeting apps (like Wallet or Mint) store and organize data — using simple file handling operations in Python.
💡 Why it's useful: This tool helps users monitor their spending patterns and keep their financial records organized — a valuable skill for personal finance management and data handling practice.
2) Learning Objectives
By completing this project, learners will:
- 🧾 Learn file handling operations: reading, writing, and appending data
- 📂 Understand how to store structured data in text or CSV format
- 🧮 Use functions to modularize and organize code
- 🕹️ Practice building a menu-driven console application
- 🔁 Apply loops, conditionals, and exception handling in a real scenario
3) Step-by-Step Explanation
Follow these steps to build the expense tracker:
- Set Up the Project – Create a Python file named expense_tracker.py
- Design Menu Options – The program should offer options: 1.Add new expense, 2.View all expenses, 3.View total expenses, 4.Exit
- Define File Structure – Each expense will be saved in a text file (expenses.txt) in the following format: Date | Category | Amount | Description
- Implement Core Functions – You'll need:
- add_expense() → Adds a new record and saves it to file
- view_expenses() → Displays all saved records
- view_total_expense() → Calculates total from the file
- Use File Handling – Use with open('expenses.txt', 'a') for adding data and with open('expenses.txt', 'r') for reading data
- Add Validation – Validate user input to ensure the amount is numeric
- Run Inside a Loop – Keep showing the menu until the user chooses to exit
4) Complete, Well-Commented, and Verified Python Code
You can copy this into a file named expense_tracker.py and run it.
# ----------------------------------------------------
# 💰 Personal Expense Tracker using File Handling
# ----------------------------------------------------
# Author: Your Name
# Level: Intermediate
# Verified: Python 3.8+
# ----------------------------------------------------
import os
from datetime import datetime
# File name for storing expenses
FILE_NAME = "expenses.txt"
def add_expense():
"""Add a new expense entry."""
print("\n--- Add New Expense ---")
date = datetime.now().strftime("%Y-%m-%d") # auto-fill today's date
category = input("Enter category (Food, Transport, etc.): ").title()
# Validate numeric input
while True:
try:
amount = float(input("Enter amount (in USD): "))
break
except ValueError:
print("❌ Invalid amount. Please enter a number.")
description = input("Enter short description: ")
# Save to file
with open(FILE_NAME, "a") as file:
file.write(f"{date} | {category} | {amount:.2f} | {description}\n")
print("✅ Expense added successfully!")
def view_expenses():
"""Display all recorded expenses."""
print("\n--- View All Expenses ---")
if not os.path.exists(FILE_NAME):
print("No expenses recorded yet!")
return
with open(FILE_NAME, "r") as file:
lines = file.readlines()
if not lines:
print("No expenses to display.")
return
print(f"{'Date':<12} | {'Category':<12} | {'Amount($)':<10} | Description")
print("-" * 55)
for line in lines:
print(line.strip())
def view_total_expense():
"""Calculate and display total spent amount."""
print("\n--- Total Expenses ---")
if not os.path.exists(FILE_NAME):
print("No expenses found!")
return
total = 0.0
with open(FILE_NAME, "r") as file:
for line in file:
parts = line.strip().split("|")
if len(parts) >= 3:
try:
total += float(parts[2])
except ValueError:
continue
print(f"💵 Total Spent: ${total:.2f}")
def main():
"""Main function to run the menu-based expense tracker."""
while True:
print("\n========== Personal Expense Tracker ==========")
print("1️⃣ Add New Expense")
print("2️⃣ View All Expenses")
print("3️⃣ View Total Expenses")
print("4️⃣ Exit")
print("==============================================")
choice = input("Enter your choice (1-4): ")
if choice == "1":
add_expense()
elif choice == "2":
view_expenses()
elif choice == "3":
view_total_expense()
elif choice == "4":
print("👋 Exiting... Have a great day managing your expenses!")
break
else:
print("❌ Invalid choice. Please enter a number from 1-4.")
# Run the program
if __name__ == "__main__":
main()
• Works perfectly in Python 3.8+
• Creates a file if it doesn't exist
• Handles invalid inputs gracefully
• Tested with multiple entries
5) Output Examples
Example 1: Adding Expense
1️⃣ Add New Expense
2️⃣ View All Expenses
3️⃣ View Total Expenses
4️⃣ Exit
==============================================
Enter your choice (1-4): 1
--- Add New Expense ---
Enter category (Food, Transport, etc.): Food
Enter amount (in USD): 12.50
Enter short description: Lunch with friends
✅ Expense added successfully!
Example 2: Viewing Expenses
Date | Category | Amount($) | Description
-------------------------------------------------------
2025-10-22 | Food | 12.50 | Lunch with friends
2025-10-22 | Transport | 5.00 | Bus ticket
Example 3: Viewing Total
💵 Total Spent: $17.50
6) Extension Challenge
🎯 Ideas to make it more advanced
Goal: Enhance your expense tracker with these features:
- Use CSV file instead of TXT: Replace the text file with a structured CSV format using the csv module
- Add Date Filtering: Allow users to view expenses for a specific month or date range
- Visualize Spending: Use Matplotlib or Pandas to generate graphs of spending by category
- GUI Version: Build a Tkinter interface for adding/viewing expenses in a table-like view
7) Summary
You have successfully built a Personal Expense Tracker that:
- Records and manages financial data
- Uses file handling for data persistence
- Encourages structured, modular programming
You learned how to:
- Create menu-based apps
- Write and read data to files
- Handle errors and invalid inputs gracefully
💡 "Small habits like tracking expenses lead to big achievements — and you just built a program to make that easier!"