|
| 1 | +import csv |
| 2 | +import os |
| 3 | + |
| 4 | +CSV_FILE = "expenses.csv" |
| 5 | + |
| 6 | +def initialize_csv(): |
| 7 | + if not os.path.exists(CSV_FILE): |
| 8 | + with open(CSV_FILE, "w", newline="") as file: |
| 9 | + writer = csv.writer(file) |
| 10 | + writer.writerow(["Date", "Description", "Amount"]) |
| 11 | + |
| 12 | +def add_expense(date, description, amount): |
| 13 | + with open(CSV_FILE, "a", newline="") as file: |
| 14 | + writer = csv.writer(file) |
| 15 | + writer.writerow([date, description, amount]) |
| 16 | + |
| 17 | +def view_expenses(): |
| 18 | + with open(CSV_FILE, "r") as file: |
| 19 | + reader = csv.reader(file) |
| 20 | + for row in reader: |
| 21 | + print(", ".join(row)) |
| 22 | + |
| 23 | +if __name__ == "__main__": |
| 24 | + initialize_csv() |
| 25 | + |
| 26 | + while True: |
| 27 | + print("\nExpense Tracker Menu:") |
| 28 | + print("1. Add Expense") |
| 29 | + print("2. View Expenses") |
| 30 | + print("3. Exit") |
| 31 | + |
| 32 | + choice = input("Enter your choice: ") |
| 33 | + |
| 34 | + if choice == "1": |
| 35 | + date = input("Enter the date (YYYY-MM-DD): ") |
| 36 | + description = input("Enter the description: ") |
| 37 | + amount = input("Enter the amount: ") |
| 38 | + |
| 39 | + add_expense(date, description, amount) |
| 40 | + print("Expense added successfully!") |
| 41 | + |
| 42 | + elif choice == "2": |
| 43 | + print("Expenses:") |
| 44 | + view_expenses() |
| 45 | + |
| 46 | + elif choice == "3": |
| 47 | + break |
| 48 | + |
| 49 | + else: |
| 50 | + print("Invalid choice. Please try again.") |
0 commit comments