← Back to Python Overview
Learn/python/Projects
intermediate Level⏱️ 12 min read⏳ 2 hr build
Python Expense Tracker Project: Step-by-Step Code & Tutorial
Create a practical Expense Tracker in Python that stores transactions in a JSON file, categorizes expenses, calculates total spending, and filters records by date or category.
✅ Prerequisites Checklist
- ✓Understanding of Python dictionaries and lists
- ✓Familiarity with file handling (open, read, write)
- ✓Knowledge of Python's json built-in module
- ✓Understanding of exception handling
📁 Folder & File Structure
expense_tracker/ ├── tracker.py ├── data.json └── README.md
📐 Architecture & Execution Blueprint
High-level data flow and component dispatch
[User Action: Add Expense] ➔ [Parse Data Dict] ➔ [Serialize to data.json] ➔ [Calculate Totals / Filters] ➔ [Console Report]
Algorithm & Process Flow
- Check if data.json exists; if not, initialize an empty list.
- Display a menu: Add Expense, View Expenses, View Summary, Exit.
- On Add Expense: prompt for amount, category, date, and description, then append to list.
- Save updated list to data.json using json.dump().
- On View Summary: sum amounts by category and display formatted totals.
- Loop until user chooses Exit.
### Step 1: Project Setup
Create a folder `expense_tracker` and a file `tracker.py`. Import `json` and `os` built-in modules at the top of the file.
### Step 2: Core Logic Implementation
Implement functions to load and save data from JSON.
```python
import json
import os
DATA_FILE = "data.json"
def load_data() -> list:
if not os.path.exists(DATA_FILE):
return []
with open(DATA_FILE, "r") as f:
return json.load(f)
def save_data(expenses: list):
with open(DATA_FILE, "w") as f:
json.dump(expenses, f, indent=4)
```
### Step 3: UI & Interaction Implementation
Create the console menu and report formatting logic.
```python
def add_expense(expenses: list):
amount = float(input("Enter amount: "))
category = input("Enter category (Food, Travel, Bills, Other): ")
desc = input("Enter description: ")
expenses.append({"amount": amount, "category": category, "desc": desc})
save_data(expenses)
print("Expense added successfully!")
```
### Step 4: Error Handling & Edge Cases
Ensure corrupted JSON files are caught gracefully and invalid numerical inputs don't crash the application.
🐛 Common Bugs & Troubleshooting
How to resolve typical implementation hurdles
| Symptom / Bug | Solution / Fix |
|---|---|
| JSONDecodeError when file is empty. | Handle exception in load_expenses and return empty list. |
| Category matching is case sensitive. | Use .title() on category strings before saving. |
⚡ How to Extend This Project
- ★Add date filtering using Python datetime module.
- ★Export summary report to a CSV file.
- ★Add budget limits per category and alert user when exceeded.
💡 Helpful AI Prompts
- 💬"How do I add monthly budgeting alerts to this script?"
- 💬"Show how to convert this JSON storage to SQLite database."
❓ Frequently Asked Questions
Q: Why use JSON instead of plain text?
JSON preserves structural data types (numbers, lists, dicts) automatically, making parsing flawless.
Q: Can multiple users access this file?
This script is designed for single-user desktop usage. Concurrent web usage would require a database like SQLite or MongoDB.