Back to Tutorials
Python

Expense Tracker in Python

Build a simple command-line expense tracker - add, view, and save your expenses to a file using Python.

~30 mins Beginner Python 3
What You'll Build
  • Add expenses with name & amount
  • View all saved expenses
  • See total spending
  • Save data to a text file
Requirements
  • Python 3 installed
  • Any text editor (VS Code recommended)
  • No extra libraries needed
Step 1

Install Python & Set Up

  1. Download Python from python.org and install it
  2. During install, check "Add Python to PATH"
  3. Open VS Code (or any editor) and create a new file: expense_tracker.py
  4. Open a terminal and run python --version to confirm it's installed
Step 2

Understand the Structure

Our tracker will have 4 simple functions:

Step 3

Write the Code

Copy this complete code into your expense_tracker.py file:

expense_tracker.py
# Expense Tracker - NKDevSpace Tutorial

FILE = "expenses.txt"

def add_expense():
    name = input("Expense name: ")
    amount = input("Amount (₹): ")
    with open(FILE, "a") as f:
        f.write(f"{name},{amount}\n")
    print(f"✅ Added: {name} - ₹{amount}\n")

def view_expenses():
    print("\n--- Your Expenses ---")
    try:
        with open(FILE, "r") as f:
            lines = f.readlines()
        if not lines:
            print("No expenses yet.")
        else:
            for i, line in enumerate(lines, 1):
                name, amount = line.strip().split(",")
                print(f"{i}. {name} - ₹{amount}")
    except FileNotFoundError:
        print("No expenses yet.")
    print()

def get_total():
    total = 0
    try:
        with open(FILE, "r") as f:
            for line in f:
                _, amount = line.strip().split(",")
                total += float(amount)
    except FileNotFoundError:
        pass
    print(f"\n💰 Total Spending: ₹{total:.2f}\n")

def main():
    while True:
        print("=== Expense Tracker ===")
        print("1. Add Expense")
        print("2. View Expenses")
        print("3. View Total")
        print("4. Exit")
        choice = input("Choose (1-4): ")

        if choice == "1":
            add_expense()
        elif choice == "2":
            view_expenses()
        elif choice == "3":
            get_total()
        elif choice == "4":
            print("Goodbye!")
            break
        else:
            print("Invalid choice. Try again.\n")

main()
Step 4

Code Explanation

Let's understand what each part of the code does:

FILE = "expenses.txt"
This creates a variable called FILE that stores the filename. All expenses will be saved into this text file. Using a variable means you only need to change the name in one place.
def add_expense():
def means we are defining a function - a reusable block of code. add_expense() asks the user to type an expense name and amount, then saves it to the file using "a" mode (append = add to end without deleting old data).
with open(FILE, "a") as f:
This opens the file safely. "a" means append mode - it adds new lines without erasing old ones. The with keyword automatically closes the file when done, so you don't have to worry about it.
f.write(f"{name},{amount}\n")
This writes one line to the file in the format name,amount. The f"..." is called an f-string - it lets you put variables directly inside text using curly braces. \n moves to the next line.
try: ... except FileNotFoundError:
This is error handling. If the file doesn't exist yet (first time running), Python would normally crash. The try/except block catches that error and instead prints a friendly message like "No expenses yet."
for i, line in enumerate(lines, 1):
enumerate gives you both the index number and the value while looping. Starting from 1 means the list shows 1, 2, 3... instead of 0, 1, 2. This makes it look like a proper numbered list.
total += float(amount)
float() converts the text amount (like "150") into a decimal number so we can do math on it. += means add to the existing total - same as writing total = total + float(amount).
while True:
This creates an infinite loop - the menu keeps showing again and again until the user picks option 4 (Exit). The break statement inside the loop is what stops it when the user wants to quit.
Step 5

Run the Program

  1. Open your terminal in the folder where you saved the file
  2. Run: python expense_tracker.py
  3. The menu will appear - try adding a few expenses
  4. Check your folder - a file called expenses.txt will be created automatically
Open expenses.txt in any text editor to see how your data is stored. Each line is one expense in the format: name,amount
Step 6

Try It Yourself - Challenges

Now that you understand the code, try these to level up:

Next Tutorial