Skip to main content

Programming fundamentals · Beginner · 18 min

Save expenses to a CSV file and load them next time

By Padding · Updated 18 Nov 2026
Python 3.15.2 · python:3.15-slim (Debian)

You will add save_expenses() and load_expenses() to the budget tracker so every expense is kept in expenses.csv between runs, the first run starts cleanly, and the file opens in any spreadsheet.

On this page

Run your budget tracker, type in a week of spending, type done, and you get a tidy summary. Run it again tomorrow and the list is empty. Everything the program knew lived in its memory, and a program's memory is cleared the moment it exits.

To remember anything between runs, a program has to write it somewhere that outlasts it: a file on disk. In this part you add two functions to the tracker. save_expenses() writes every expense to a file called expenses.csv when you finish, and load_expenses() reads them back when the tracker starts. You also handle the very first run, when there is no file yet.

CSV stands for comma-separated values. It is plain text: one line per row, with commas between the columns. Spreadsheet apps open it directly, so by the end you can look at your spending in a spreadsheet as well as in the terminal.

The examples use python3, as in the earlier parts. On Windows outside WSL, type py instead.

Step 1 · Start from the part 6 tracker

Go to the tracker folder (the command creates it if you are starting here):

Bash
mkdir -p ~/budget-tracker
cd ~/budget-tracker

The block below is budget.py exactly as it stood at the end of part 6, docstrings and all. If you finished part 6 and kept your file as it was, it already matches and you can skip writing it again. If you are starting here, or you changed your copy, write this version so your screen matches every output in this part. Paste the whole block into the terminal, or copy the lines between the two PY markers into your editor and save them as budget.py:

Bash
cat > budget.py <<'PY'
# budget.py: a personal budget tracker (part 6)
currency = "NGN"


def ask_for_expense():
    """Ask for one expense. Return it as a dictionary, or None after done."""
    item = input("Item (or done): ")
    if item.strip().lower() == "done":
        return None
    category = input("Category: ").lower()
    amount = int(input("Amount: "))
    return {"item": item, "category": category, "amount": amount}


def total_spent(expenses):
    """Return the sum of all the amounts."""
    spent = 0
    for expense in expenses:
        spent += expense["amount"]
    return spent


def total_by_category(expenses):
    """Return a dictionary of category name to amount spent."""
    totals = {}
    for expense in expenses:
        category = expense["category"]
        if category in totals:
            totals[category] = totals[category] + expense["amount"]
        else:
            totals[category] = expense["amount"]
    return totals


def print_summary(expenses):
    """Print the table, the biggest expense and the totals per category."""
    print()
    print("Spending summary")
    print("-" * 32)
    for expense in expenses:
        print(f"{expense['item']:<14}{expense['category']:<10}{expense['amount']:>8,}")
    print("-" * 32)
    print(f"{len(expenses)} expenses, spent {total_spent(expenses):,}")

    if len(expenses) > 0:
        biggest = expenses[0]
        for expense in expenses:
            if expense["amount"] > biggest["amount"]:
                biggest = expense
        print(f"Biggest: {biggest['item']} ({biggest['amount']:,})")

    totals = total_by_category(expenses)
    print()
    print("By category")
    for category, total in totals.items():
        print(f"{category:<24}{total:>8,}")


def main():
    budget = int(input("Monthly budget: "))
    expenses = []
    while True:
        expense = ask_for_expense()
        if expense is None:
            break
        expenses.append(expense)

    print_summary(expenses)

    left = budget - total_spent(expenses)
    print()
    if left < 0:
        print(f"Warning: over budget by {currency} {-left:,}")
    elif left < budget / 10:
        print(f"Careful: only {currency} {left:,} left")
    else:
        print(f"You have {currency} {left:,} left this month.")


if __name__ == "__main__":
    main()
PY

A quick reminder of the pieces you built in parts 3 to 6:

  • ask_for_expense() asks three questions and returns one expense as a dictionary, or None when you type done.
  • total_by_category(expenses) adds up the amounts per category and returns a new dictionary such as {"travel": 1500, "food": 12000}.
  • total_spent(expenses) returns the sum of all the amounts.
  • print_summary(expenses) prints the table of expenses, the count and total, the biggest one and the totals per category.
  • main() asks for the budget, loops until done, calls print_summary(expenses) and then prints what is left of the budget in your currency, with a warning when it runs low.
  • The text in triple quotes under each def line is a docstring: a short note saying what the function does.
  • if __name__ == "__main__": runs main() only when you start the file with python3 budget.py. When another file or the Python prompt imports budget, the functions are available but nothing runs. Part 8 relies on this to test total_by_category.

Run it and enter two expenses, as before:

Bash
python3 budget.py

Type 50000 for the budget, then Transport, travel, 1500, then Rice, beans, food, 12000, then done.

Check it worked

The Spending summary table lists Transport (travel, 1,500) and Rice, beans (food, 12,000). Below it you see 2 expenses, spent 13,500, Biggest: Rice, beans (12,000), the totals under By category and, on the last line, You have NGN 36,500 left this month. Now run python3 budget.py again: the two expenses are gone. That is the problem this part fixes.

Step 2 · Write a CSV file with the csv module

Try writing a CSV file in a scratch script before changing the tracker. Python's standard library has a csv module, so there is nothing to install:

Bash
cat > csv_try.py <<'PY'
import csv

rows = [
    ["item", "category", "amount"],
    ["Transport", "travel", 1500],
    ["Rice, beans", "food", 12000],
]

with open("try.csv", "w", newline="", encoding="utf-8") as file:
    writer = csv.writer(file)
    writer.writerows(rows)

print("Wrote try.csv")
PY
python3 csv_try.py
cat try.csv

Line by line:

  • import csv loads the module. Every import goes at the top of a file, so the rest of the file can use it.
  • rows is a list of lists. Each inner list is one row of the file. The first row holds the column names, called the header.
  • open("try.csv", "w", ...) opens the file for writing. "w" means write: Python creates the file if it is missing and empties it if it already exists. That second half matters later.
  • newline="" hands control of line endings to the csv module. Without it, Windows adds an extra blank line after every row. The Python documentation asks for it whenever you open a file for csv.
  • encoding="utf-8" fixes how letters are turned into bytes, so names in any language (Àkàrà, Café, Ügyfél) are written and read the same way on every computer.
  • with ... as file: gives the open file the name file for the indented lines below. When those lines finish, Python closes the file for you, which also makes sure everything has been written to disk. You never call close() yourself.
  • csv.writer(file) makes a writer object that turns lists into CSV lines, and writer.writerows(rows) writes all the rows in one go.

Check it worked

The script prints Wrote try.csv, and cat try.csv shows:

Text
item,category,amount
Transport,travel,1500
"Rice, beans",food,12000

Look at the third line. Rice, beans has a comma in it, so the csv module wrapped it in double quotes. Without the quotes, a program reading the file would see four columns on that line. This is why you use the module instead of building lines yourself with f-strings.

Step 3 · Read the file back and notice that numbers come back as text

Now read try.csv into dictionaries, the same shape the tracker uses for each expense:

Bash
cat > csv_read.py <<'PY'
import csv

with open("try.csv", newline="", encoding="utf-8") as file:
    reader = csv.DictReader(file)
    for row in reader:
        print(row)
        print(type(row["amount"]))
PY
python3 csv_read.py

What is new:

  • open("try.csv", ...) has no "w" this time. With no mode, a file opens for reading, and reading never changes it.
  • csv.DictReader(file) reads the header line and uses it as the keys. Each later line becomes a dictionary like {"item": "Transport", "category": "travel", "amount": "1500"}.
  • for row in reader: hands you one row at a time, as a for loop over a list would.
  • type(row["amount"]) shows what kind of value the amount is.

Check it worked

You see two dictionaries, each followed by <class 'str'>:

Text
{'item': 'Transport', 'category': 'travel', 'amount': '1500'}
<class 'str'>
{'item': 'Rice, beans', 'category': 'food', 'amount': '12000'}
<class 'str'>

The quotes around '1500' give it away: the amount came back as text. A file holds only characters, just as the keyboard sends only characters, so you meet the same problem as with input() in part 2. If the tracker used these rows as they are, print_summary() would stop with an error as soon as it tried to format the first amount with :,, and total_spent() could not add text to a number either. The fix is the same as in part 2: convert with int(). The item and category values are meant to be text, so they need nothing.

Step 4 · Add save_expenses() to the tracker

Back to budget.py. The tracker needs a function that writes the whole list of expenses to expenses.csv, and main() needs to call it after you type done. Replace budget.py with this version. Everything from part 6 is still there, unchanged apart from the comment on the first line; the new lines are the imports and settings at the top, save_expenses(), and two lines in main(). They are explained after the code:

Bash
cat > budget.py <<'PY'
# budget.py: a personal budget tracker (part 7)
import csv
from pathlib import Path

currency = "NGN"
EXPENSES_FILE = Path("expenses.csv")
FIELDS = ["item", "category", "amount"]


def ask_for_expense():
    """Ask for one expense. Return it as a dictionary, or None after done."""
    item = input("Item (or done): ")
    if item.strip().lower() == "done":
        return None
    category = input("Category: ").lower()
    amount = int(input("Amount: "))
    return {"item": item, "category": category, "amount": amount}


def total_spent(expenses):
    """Return the sum of all the amounts."""
    spent = 0
    for expense in expenses:
        spent += expense["amount"]
    return spent


def total_by_category(expenses):
    """Return a dictionary of category name to amount spent."""
    totals = {}
    for expense in expenses:
        category = expense["category"]
        if category in totals:
            totals[category] = totals[category] + expense["amount"]
        else:
            totals[category] = expense["amount"]
    return totals


def print_summary(expenses):
    """Print the table, the biggest expense and the totals per category."""
    print()
    print("Spending summary")
    print("-" * 32)
    for expense in expenses:
        print(f"{expense['item']:<14}{expense['category']:<10}{expense['amount']:>8,}")
    print("-" * 32)
    print(f"{len(expenses)} expenses, spent {total_spent(expenses):,}")

    if len(expenses) > 0:
        biggest = expenses[0]
        for expense in expenses:
            if expense["amount"] > biggest["amount"]:
                biggest = expense
        print(f"Biggest: {biggest['item']} ({biggest['amount']:,})")

    totals = total_by_category(expenses)
    print()
    print("By category")
    for category, total in totals.items():
        print(f"{category:<24}{total:>8,}")


def save_expenses(expenses):
    """Write every expense to EXPENSES_FILE, replacing what was there."""
    with open(EXPENSES_FILE, "w", newline="", encoding="utf-8") as file:
        writer = csv.DictWriter(file, fieldnames=FIELDS)
        writer.writeheader()
        writer.writerows(expenses)


def main():
    budget = int(input("Monthly budget: "))
    expenses = []
    while True:
        expense = ask_for_expense()
        if expense is None:
            break
        expenses.append(expense)

    save_expenses(expenses)
    print(f"Saved to {EXPENSES_FILE}: {len(expenses)} expense(s).")
    print_summary(expenses)

    left = budget - total_spent(expenses)
    print()
    if left < 0:
        print(f"Warning: over budget by {currency} {-left:,}")
    elif left < budget / 10:
        print(f"Careful: only {currency} {left:,} left")
    else:
        print(f"You have {currency} {left:,} left this month.")


if __name__ == "__main__":
    main()
PY

The new parts:

  • from pathlib import Path brings in Path, which represents a file's location. You use it in the next step to ask whether the file exists.
  • EXPENSES_FILE = Path("expenses.csv") and FIELDS = [...] sit outside every function, like currency, so all functions can read them. The capital letters are a Python habit that says "this is a setting; do not change it while the program runs". If you want a different file name, you change it in one place.
  • csv.DictWriter(file, fieldnames=FIELDS) is the writing partner of DictReader. It takes dictionaries instead of lists and uses fieldnames to decide the column order. Each expense already is a dictionary with exactly these three keys, so nothing needs converting on the way out.
  • writer.writeheader() writes the line item,category,amount. writer.writerows(expenses) writes one line per expense.
  • In main(), save_expenses(expenses) runs after the loop ends and before print_summary(expenses), so it saves everything you typed. len(expenses) counts the items in the list for the message. Writing expense(s) keeps the message correct whether you saved one expense or twenty.

Run it with the same two expenses, then look at the file it made:

Bash
python3 budget.py
cat expenses.csv

Now run it once more and enter a single expense, Data bundle, phone, 2000, then done, and look at the file again:

Bash
python3 budget.py
cat expenses.csv

Check it worked

After the first run the program prints Saved to expenses.csv: 2 expense(s)., and the file holds a header and two rows, just like try.csv. After the second run the program prints Saved to expenses.csv: 1 expense(s). and the file holds only the header and Data bundle,phone,2000. Transport and rice have gone.

That is a real bug, and worth seeing once. Each run starts with an empty list, and "w" empties the file before writing, so saving on its own replaces last session's spending with today's. The tracker has to load the old expenses first, add the new ones to them, and then save the full list.

Step 5 · Add load_expenses() and handle the first run

Here is the reading function on its own, so you can study it before it goes into the file:

Python
def load_expenses():
    if not EXPENSES_FILE.exists():
        return []
    expenses = []
    with open(EXPENSES_FILE, newline="", encoding="utf-8") as file:
        reader = csv.DictReader(file)
        for row in reader:
            row["amount"] = int(row["amount"])
            expenses.append(row)
    return expenses

Line by line:

  • EXPENSES_FILE.exists() is True if the file is there and False if it is not. The first time anyone runs the tracker there is no expenses.csv, and opening a missing file for reading stops the program with FileNotFoundError. So the function checks first. not turns True into False and False into True, so if not EXPENSES_FILE.exists(): reads "if the file does not exist". In that case it returns an empty list, which is exactly what a new tracker should start with.
  • expenses = [] makes the list that the loop fills.
  • The with open(...) line has no "w", so it reads and never empties the file.
  • row["amount"] = int(row["amount"]) replaces the text "1500" with the number 1500, the fix from the previous step.
  • expenses.append(row) adds the row, now a proper expense, to the list, and return expenses hands the whole list back to whoever called the function.

main() changes at the top: before asking for the budget it loads whatever was saved last time, and the expenses = [] line goes, because the loaded list takes its place. Replace budget.py with the finished version for this part:

Bash
cat > budget.py <<'PY'
# budget.py: a personal budget tracker (part 7)
import csv
from pathlib import Path

currency = "NGN"
EXPENSES_FILE = Path("expenses.csv")
FIELDS = ["item", "category", "amount"]


def ask_for_expense():
    """Ask for one expense. Return it as a dictionary, or None after done."""
    item = input("Item (or done): ")
    if item.strip().lower() == "done":
        return None
    category = input("Category: ").lower()
    amount = int(input("Amount: "))
    return {"item": item, "category": category, "amount": amount}


def total_spent(expenses):
    """Return the sum of all the amounts."""
    spent = 0
    for expense in expenses:
        spent += expense["amount"]
    return spent


def total_by_category(expenses):
    """Return a dictionary of category name to amount spent."""
    totals = {}
    for expense in expenses:
        category = expense["category"]
        if category in totals:
            totals[category] = totals[category] + expense["amount"]
        else:
            totals[category] = expense["amount"]
    return totals


def print_summary(expenses):
    """Print the table, the biggest expense and the totals per category."""
    print()
    print("Spending summary")
    print("-" * 32)
    for expense in expenses:
        print(f"{expense['item']:<14}{expense['category']:<10}{expense['amount']:>8,}")
    print("-" * 32)
    print(f"{len(expenses)} expenses, spent {total_spent(expenses):,}")

    if len(expenses) > 0:
        biggest = expenses[0]
        for expense in expenses:
            if expense["amount"] > biggest["amount"]:
                biggest = expense
        print(f"Biggest: {biggest['item']} ({biggest['amount']:,})")

    totals = total_by_category(expenses)
    print()
    print("By category")
    for category, total in totals.items():
        print(f"{category:<24}{total:>8,}")


def save_expenses(expenses):
    """Write every expense to EXPENSES_FILE, replacing what was there."""
    with open(EXPENSES_FILE, "w", newline="", encoding="utf-8") as file:
        writer = csv.DictWriter(file, fieldnames=FIELDS)
        writer.writeheader()
        writer.writerows(expenses)


def load_expenses():
    """Return the saved expenses, or an empty list if there is no file yet."""
    if not EXPENSES_FILE.exists():
        return []
    expenses = []
    with open(EXPENSES_FILE, newline="", encoding="utf-8") as file:
        reader = csv.DictReader(file)
        for row in reader:
            row["amount"] = int(row["amount"])
            expenses.append(row)
    return expenses


def main():
    expenses = load_expenses()
    if expenses:
        print(f"Loaded from {EXPENSES_FILE}: {len(expenses)} expense(s).")
    else:
        print("No saved expenses yet. Starting a new list.")

    budget = int(input("Monthly budget: "))
    while True:
        expense = ask_for_expense()
        if expense is None:
            break
        expenses.append(expense)

    save_expenses(expenses)
    print(f"Saved to {EXPENSES_FILE}: {len(expenses)} expense(s).")
    print_summary(expenses)

    left = budget - total_spent(expenses)
    print()
    if left < 0:
        print(f"Warning: over budget by {currency} {-left:,}")
    elif left < budget / 10:
        print(f"Careful: only {currency} {left:,} left")
    else:
        print(f"You have {currency} {left:,} left this month.")


if __name__ == "__main__":
    main()
PY

In main(), if expenses: is true when the list has at least one item and false when it is empty, so the tracker tells you which situation it is in. The rest of main() is unchanged: new expenses are appended to the loaded list, and save_expenses() writes old and new together.

The expenses.csv left over from the last step holds only the test row, so delete it and see what a brand-new user sees. This removes only that one file in the tracker folder, which this part created:

Bash
rm expenses.csv

Run the tracker and enter 50000, then Transport, travel, 1500, then Rice, beans, food, 12000, then done:

Bash
python3 budget.py

Now close the session and come back, as you would the next day. Run it again with 50000, then Àkàrà, food, 800, then Data bundle, phone, 2000, then done:

Bash
python3 budget.py

Check it worked

The first run starts with No saved expenses yet. Starting a new list. and prints Saved to expenses.csv: 2 expense(s). before the summary. The second run starts with Loaded from expenses.csv: 2 expense(s)., saves 4, and its summary lists all four expenses, with food at 12,800 under By category (rice and àkàrà together), 4 expenses, spent 16,300 and You have NGN 33,700 left this month. The accented Àkàrà comes back exactly as you typed it, thanks to encoding="utf-8".

Step 6 · Open expenses.csv in a spreadsheet

Look at the file the tracker keeps for you:

Bash
cat expenses.csv
wc -l expenses.csv

wc -l counts lines: one header plus one per expense.

Now open expenses.csv in a spreadsheet app: LibreOffice Calc, Excel, Numbers, or Google Sheets (upload the file first). The file is in your budget-tracker folder inside your home folder. You can also copy it to a phone and open it in a spreadsheet app there; at a few hundred bytes for a month of expenses, it costs next to nothing to send over prepaid data.

A few things to know:

  • If accented letters such as À look garbled in Excel, it has guessed the wrong text encoding. Changing "utf-8" to "utf-8-sig" in both open() lines makes Python add a short marker at the start of the file that tells spreadsheet apps it is UTF-8, and still reads files without the marker.
  • If everything lands in one column, your spreadsheet may expect semicolons, which is common where a comma is the decimal separator. Use the app's import option and choose comma as the separator.
  • You can fix a typo in the spreadsheet, but save as CSV, not in the spreadsheet's own format, and keep the amount column as plain digits. A value such as 1,500 or ₦1500 stops the tracker with a ValueError when it loads. Part 8 makes the tracker cope with that.

Check it worked

cat shows the header and four rows, and wc -l prints 5 expenses.csv (macOS adds spaces before the number). In the spreadsheet you see three columns headed item, category and amount, four rows below them, and Rice, beans sitting in one cell, because the quotes kept its comma inside the item.

Step 7 · Avoid the file mistakes beginners make

Most file bugs come from a handful of causes. Try the most common one: running the tracker from a different folder. Make a throwaway folder and run the tracker from there, typing 50000 and then done:

Bash
mkdir -p ~/budget-elsewhere-demo
cd ~/budget-elsewhere-demo
python3 ~/budget-tracker/budget.py
ls

The tracker says No saved expenses yet, and ls shows a new, almost empty expenses.csv in the throwaway folder. A name like "expenses.csv" is looked up in the folder your terminal is in, not the folder the script lives in. Your real file is untouched; the tracker simply looked in the wrong place. Go back and remove the throwaway folder:

Bash
cd ~/budget-tracker
rm -r ~/budget-elsewhere-demo

The others to watch for:

  • Opening with "w" when you meant to read. "w" empties the file the moment it opens, before you write anything. Only save_expenses() uses "w".
  • Leaving out newline="". On Windows every row gets a blank line after it, and quoted values that contain line breaks are read wrongly.
  • Leaving out int() when loading. Amounts stay text, and the tracker stops with an error as soon as the summary tries to format or add them.
  • Stopping with Ctrl+C. The tracker saves only after you type done, so expenses typed in a session you interrupt are lost. The file from the previous session stays as it was.

Finally, remove the scratch files from this part. Keep budget.py and expenses.csv, because part 8 builds on both:

Bash
rm -f csv_try.py csv_read.py try.csv
ls

Check it worked

The throwaway run printed No saved expenses yet, while your real data was safe. Back in ~/budget-tracker, run python3 budget.py: it says Loaded from expenses.csv: 4 expense(s). The final ls lists budget.py and expenses.csv, plus PLAN.txt from part 1 and branch-tests.txt from part 3 if you made them. You can now tick off line 7 of that plan.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.