-
Notifications
You must be signed in to change notification settings - Fork 38
/
Copy pathexpensetracker.py
40 lines (34 loc) · 1.22 KB
/
expensetracker.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import json
from datetime import datetime
class ExpenseManager:
def __init__(self):
self.expense_list = []
self.load_expenses()
def load_expenses(self):
"""Load expenses from a JSON file."""
try:
with open('expenses.json', 'r') as file:
self.expense_list = json.load(file)
except FileNotFoundError:
self.expense_list = []
def save_expenses(self):
"""Save the current expenses to a JSON file."""
with open('expenses.json', 'w') as file:
json.dump(self.expense_list, file)
def add_expense(self, amount, category):
"""Add a new expense to the tracker."""
expense = {
'amount': amount,
'category': category,
'date': str(datetime.now())
}
self.expense_list.append(expense)
self.save_expenses()
def display_expenses(self):
"""Display all recorded expenses."""
for expense in self.expense_list:
print(f"Amount: {expense['amount']}, Category: {expense['category']}, Date: {expense['date']}")
if __name__ == "__main__":
manager = ExpenseManager()
manager.add_expense(50, 'Food')
manager.display_expenses()