Build a simple command-line expense tracker - add, view, and save your expenses to a file using Python.
python --version to confirm it's installedOur tracker will have 4 simple functions:
Copy this complete code into your expense_tracker.py file:
# 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()
Let's understand what each part of the code does:
FILE = "expenses.txt"def add_expense():with open(FILE, "a") as f:f.write(f"{name},{amount}\n")try: ... except FileNotFoundError:for i, line in enumerate(lines, 1):total += float(amount)while True:python expense_tracker.pyNow that you understand the code, try these to level up: