Python Expense Tracker
Table of Contents
In the last lesson, Python Calculator Application, we built a calculator with calculation history. Now we will build an expense tracker that saves and summarizes spending data.
In this tutorial, we will build a Python Expense Tracker from scratch using VS Code. This is a practical beginner project that teaches CSV file handling, dictionaries, lists, loops, functions, and data grouping. By the end, we will have a working expense manager that can add expenses, view them, show totals, group by category, and save everything to a file.
❓ What Is an Expense Tracker?
An Expense Tracker is a program that helps us record and manage our daily spending. We can add expenses with an amount, category, and description. Then we can view all expenses, see total spending, and see how much we spent in each category.
Think of it like a digital spending diary. Instead of writing on paper, we type our expenses into the program. And the program keeps a record for us.
Expense trackers are useful for personal budgeting, small business accounting, and financial planning. They are simple but very powerful.
✨ Features of Our Python Expense Tracker
Our Expense Tracker will have these features:
- Add an expense with amount, category, and description
- View all expenses in a table
- Show total spending
- Show spending by category
- Save expenses to a CSV file
- Load expenses when the program starts
🗂️ Project Folder Structure
We will create a folder for our project. Inside it, we will have one Python file and one CSV file.
expense_tracker/ tracker.py expenses.csvThe expenses.csv file stores our expenses. It will be created automatically when we save our first expense.
Let us set up the project in VS Code.
🛠️ Setting Up the Project in VS Code
💻 Step 1: Open VS Code
If we do not have VS Code installed, we can download it from code.visualstudio.com. It is free.
Once installed, open VS Code.
📁 Step 2: Create a New Folder
- Click on File in the top menu.
- Click Open Folder.
- Navigate to where we want to keep our project (like Desktop or Documents).
- Click New Folder.
- Name it
expense_tracker. - Click Select Folder.
Now VS Code is open with our new empty folder.
📝 Step 3: Create the Python File
- In the left sidebar, we see our folder name
expense_tracker. - Right-click on the folder name.
- Click New File.
- Name it
tracker.py. - Press Enter.
Now we have an empty tracker.py file ready for code.
⌨️ Step 4: Open the Integrated Terminal
- Click on Terminal in the top menu.
- Click New Terminal.
A terminal panel opens at the bottom. It is already inside our expense_tracker folder. So we do not need to cd anywhere.
Now we are ready to write code.
🧱 How to Create the Expense Tracker in Python (Step by Step)
We will write the code in small steps. Before each step, we will explain what we are doing and why. We will mention which file we are editing (always tracker.py in this project).
📦 Step 1: Import Required Modules
We need three modules. csv for reading and writing CSV files, os for checking if the file exists, and datetime for adding the current date to each expense.
import csvimport osfrom datetime import datetime🗃️ Step 2: Define the Expenses File
We will store expenses in a file called expenses.csv. Let us define it as a constant.
EXPENSES_FILE = "expenses.csv"🔄 Step 3: Create a Function to Load Expenses
When the program starts, we want to show the user their existing expenses. So we read the CSV file into a list of dictionaries.
def load_expenses(): if not os.path.exists(EXPENSES_FILE): return [] with open(EXPENSES_FILE, "r") as file: reader = csv.DictReader(file) return list(reader)💾 Step 4: Create a Function to Save Expenses
Whenever we add an expense, we save the changes so they are not lost.
def save_expenses(expenses): with open(EXPENSES_FILE, "w", newline="") as file: fieldnames = ["date", "amount", "category", "description"] writer = csv.DictWriter(file, fieldnames=fieldnames) writer.writeheader() writer.writerows(expenses)➕ Step 5: Create a Function to Add an Expense
The user types an amount, category, and description. We add it to our list and save the updated list to the file.
def add_expense(expenses): try: amount = float(input("Enter amount: ")) except ValueError: print("Please enter a valid number") return category = input("Enter category (food, transport, etc.): ").strip() description = input("Enter description: ").strip() date = datetime.now().strftime("%Y-%m-%d")
expense = { "date": date, "amount": amount, "category": category, "description": description } expenses.append(expense) save_expenses(expenses) print(f"Expense added: {amount} for {category}")👀 Step 6: Create a Function to View All Expenses
The user needs to see what expenses they have. We loop through the list and print each expense in a formatted table.
def view_expenses(expenses): if not expenses: print("No expenses yet") return print("\nAll Expenses:") print("-" * 60) print(f"{'Date':<12} {'Amount':>10} {'Category':<15} {'Description'}") print("-" * 60) for e in expenses: print(f"{e['date']:<12} {float(e['amount']):>10.2f} {e['category']:<15} {e['description']}") print("-" * 60)💰 Step 7: Create a Function to Show Total Spending
We sum all amounts and print the total.
def show_total(expenses): if not expenses: print("No expenses yet") return total = sum(float(e["amount"]) for e in expenses) print(f"\nTotal spending: ${total:.2f}")🏷️ Step 8: Create a Function to Show Spending by Category
We group expenses by category and sum them.
def show_by_category(expenses): if not expenses: print("No expenses yet") return totals = {} for e in expenses: category = e["category"] amount = float(e["amount"]) totals[category] = totals.get(category, 0) + amount
print("\nSpending by Category:") print("-" * 40) for category, total in sorted(totals.items()): print(f"{category:<20} ${total:.2f}") print("-" * 40)📋 Step 9: Create the Main Menu Function
This is the control center. It shows the options to the user and calls the right function based on their choice.
def main(): expenses = load_expenses() while True: print("\n===== EXPENSE TRACKER =====") print("1. Add expense") print("2. View all expenses") print("3. Show total") print("4. Show by category") print("5. Exit") choice = input("Enter your choice: ").strip()
if choice == "1": add_expense(expenses) elif choice == "2": view_expenses(expenses) elif choice == "3": show_total(expenses) elif choice == "4": show_by_category(expenses) elif choice == "5": print("Goodbye!") break else: print("Invalid choice")🚀 Step 10: Run the Expense Tracker Program
Finally, let us add the program entry point.
if __name__ == "__main__": main()🧩 Complete Python Expense Tracker Code
Now our complete tracker.py file looks like this.
import csvimport osfrom datetime import datetime
EXPENSES_FILE = "expenses.csv"
def load_expenses(): if not os.path.exists(EXPENSES_FILE): return [] with open(EXPENSES_FILE, "r") as file: reader = csv.DictReader(file) return list(reader)
def save_expenses(expenses): with open(EXPENSES_FILE, "w", newline="") as file: fieldnames = ["date", "amount", "category", "description"] writer = csv.DictWriter(file, fieldnames=fieldnames) writer.writeheader() writer.writerows(expenses)
def add_expense(expenses): try: amount = float(input("Enter amount: ")) except ValueError: print("Please enter a valid number") return category = input("Enter category (food, transport, etc.): ").strip() description = input("Enter description: ").strip() date = datetime.now().strftime("%Y-%m-%d")
expense = { "date": date, "amount": amount, "category": category, "description": description } expenses.append(expense) save_expenses(expenses) print(f"Expense added: {amount} for {category}")
def view_expenses(expenses): if not expenses: print("No expenses yet") return print("\nAll Expenses:") print("-" * 60) print(f"{'Date':<12} {'Amount':>10} {'Category':<15} {'Description'}") print("-" * 60) for e in expenses: print(f"{e['date']:<12} {float(e['amount']):>10.2f} {e['category']:<15} {e['description']}") print("-" * 60)
def show_total(expenses): if not expenses: print("No expenses yet") return total = sum(float(e["amount"]) for e in expenses) print(f"\nTotal spending: ${total:.2f}")
def show_by_category(expenses): if not expenses: print("No expenses yet") return totals = {} for e in expenses: category = e["category"] amount = float(e["amount"]) totals[category] = totals.get(category, 0) + amount
print("\nSpending by Category:") print("-" * 40) for category, total in sorted(totals.items()): print(f"{category:<20} ${total:.2f}") print("-" * 40)
def main(): expenses = load_expenses() while True: print("\n===== EXPENSE TRACKER =====") print("1. Add expense") print("2. View all expenses") print("3. Show total") print("4. Show by category") print("5. Exit") choice = input("Enter your choice: ").strip()
if choice == "1": add_expense(expenses) elif choice == "2": view_expenses(expenses) elif choice == "3": show_total(expenses) elif choice == "4": show_by_category(expenses) elif choice == "5": print("Goodbye!") break else: print("Invalid choice")
if __name__ == "__main__": main()▶️ How to Run the Expense Tracker in VS Code
We have two ways to run the program.
⚡ Way 1: Using the Terminal
In the VS Code terminal, type:
python tracker.py🖱️ Way 2: Using the Run Button
- Open
tracker.pyin the editor. - Look at the top right corner. There is a small play button (triangle).
- Click it. VS Code will run the file in the terminal.
Both ways work. Use whichever we prefer.
🖥️ Example Output
===== EXPENSE TRACKER =====1. Add expense2. View all expenses3. Show total4. Show by category5. ExitEnter your choice: 1Enter amount: 25.50Enter category (food, transport, etc.): foodEnter description: LunchExpense added: 25.5 for food
===== EXPENSE TRACKER =====...Enter your choice: 2
All Expenses:------------------------------------------------------------Date Amount Category Description------------------------------------------------------------2025-01-15 25.50 food Lunch------------------------------------------------------------That is our Expense Tracker. It is simple but complete. And we built it entirely in VS Code.
🎯 Exercises for Practice
Try these exercises to improve the Expense Tracker.
- Add a monthly report that groups expenses by month.
- Add an income tracker alongside expenses.
- Add budget limits for each category with warnings when exceeded.
- Add a search feature to find expenses by keyword.
- Add a delete expense option by index number.
- Add an edit expense option to update amount, category, or description.
- Export a summary report to a text file.
Now let us build the next project: the Student Management System. We will also use VS Code for that.
Next, we will build a Python Student Management System with complete record-management operations.