๐ŸŽ‰ Welcome to PyVerse! Start Learning Today

Personal Expense Tracker with File Handling

Intermediate

Build 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:

  1. Set Up the Project โ€“ Create a Python file named expense_tracker.py
  2. Design Menu Options โ€“ The program should offer options: 1.Add new expense, 2.View all expenses, 3.View total expenses, 4.Exit
  3. Define File Structure โ€“ Each expense will be saved in a text file (expenses.txt) in the following format: Date | Category | Amount | Description
  4. 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
  5. Use File Handling โ€“ Use with open('expenses.txt', 'a') for adding data and with open('expenses.txt', 'r') for reading data
  6. Add Validation โ€“ Validate user input to ensure the amount is numeric
  7. 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()

โœ… Verified:
โ€ข 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

========== Personal Expense Tracker ==========
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

--- View All 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 Expenses ---
๐Ÿ’ต 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!"