Build small tools

Inspect an Expense CSV Without Uploading It

Parse a small fictional expense CSV, validate decimal amounts and total each currency separately without sending the file to a service.

By Build Next Stack · Editorial approach
Published · Updated

An expense-file exercise is useful when it makes parsing decisions explicit. The example below reads a small CSV, checks its columns and amounts, and prints totals grouped by currency. It runs as a local command; there is no upload or connection to a bank account.

The fixture is fictional and deliberately includes a quoted comma, a negative refund and a second currency. Those details expose rules that a simple split-on-comma script or one grand total would miss.

Choose a narrow input format

The header must contain date, category, amount, currency and note in that order. Each amount must have exactly two decimal places, optionally preceded by a minus sign. The currency field must be three uppercase letters.

That last rule checks shape, not membership in an official currency list. The date column is carried through but is not calendar-validated in this example. These boundaries should be documented before someone assumes the parser verifies every property of an accounting export.

Let a CSV parser handle the structure

Python’s CSV module understands quoted fields and escaped separators. The file is opened with the documented newline handling and UTF-8-with-optional-BOM decoding. A note containing a comma remains one cell rather than becoming an extra column.

The script rejects rows with missing or extra columns. It does not silently skip a malformed record and present the remaining total as complete. If an input fails, fix or explicitly transform a copy according to the source system’s format instead of suppressing the exception.

Keep decimal input as decimal input

The amounts are converted directly from text to Decimal, rather than first passing through a binary float. Each addition uses a local decimal context sized for the larger operand plus a carry digit, with inexact arithmetic rejected. Because accepted amounts have exactly two decimal places, large totals retain their cents instead of silently hitting the default precision limit. The input grammar rejects NaN, infinity and informal text; localized number formats remain outside this example.

A comma used as a decimal separator, a thousands separator or a currency symbol will require a separate documented policy. Do not remove arbitrary punctuation until the input happens to parse; that can change the meaning of a number.

Read the result by currency

Fixture component Effect on the result
USD 12.50 and 7.25 Increase the USD total
USD -2.00 refund Reduces that same currency total
EUR 9.00 Remains a separate total
Quoted descriptive note Does not affect numeric aggregation

The executed sample reports four records, USD 17.75 and EUR 9.00. Replacing an amount with NaN caused the test to fail. No exchange rate was inferred, and the program does not combine the currencies into a single spending figure.

Preview without changing the source

The CSV preview tool can inspect a small fictional copy and show exact duplicate rows. It does not calculate this script’s totals or determine whether a repeated expense is an error. Two identical charges can represent two real events.

If duplicates need review, use the explicit dry-run exercise. Decide the record-identity rule before removing rows. Whole-row equality is a mechanical rule, not an accounting judgment.

Expand only after adding a fixture

A useful next feature might group by category within each currency. Write the expected result from a tiny fixture first, then change the program. The test-command guide shows how to preserve a behavior check so later changes cannot silently alter it.

Keep real customer records and payment details out of shared examples. Local processing means this script does not transmit the input; it does not mean the device, terminal history, downloaded files or every other application on the computer is confidential.

Finally, retain the original export. The printed summary is a derived view with a deliberately limited schema, not a substitute for source records or a certified financial report.

Complete lab files

fixtures/expenses.csv

date,category,amount,currency,note
2026-11-01,hosting,12.50,USD,"shared, demo"
2026-11-02,books,7.25,USD,guide
2026-11-03,books,-2.00,USD,refund
2026-11-04,hosting,9.00,EUR,sample

expense-csv/summarize.py

import csv, json, re, sys
from decimal import Decimal, localcontext, Inexact
from pathlib import Path
path = Path(sys.argv[1])
totals = {}
count = 0
with path.open(encoding='utf-8-sig', newline='') as f:
    reader = csv.DictReader(f, strict=True)
    if reader.fieldnames != ['date', 'category', 'amount', 'currency', 'note']:
        raise ValueError('Unexpected header')
    for row in reader:
        if None in row or any((v is None for v in row.values())):
            raise ValueError('Wrong column count')
        if not re.fullmatch('-?\\d+\\.\\d{2}', row['amount']):
            raise ValueError('Amount must have two decimal places')
        if not re.fullmatch('[A-Z]{3}', row['currency']):
            raise ValueError('Currency must be three uppercase letters')
        key = row['currency']
        amount = Decimal(row['amount'])
        previous = totals.get(key, Decimal('0'))
        with localcontext() as context:
            context.prec = max(len(previous.as_tuple().digits), len(amount.as_tuple().digits)) + 1
            context.traps[Inexact] = True
            totals[key] = previous + amount
        count += 1
print(json.dumps({'rows': count, 'totals': {k: format(v, '.2f') for k, v in sorted(totals.items())}}, sort_keys=True))

Run the example

python3 expense-csv/summarize.py fixtures/expenses.csv

Observed result

{"rows": 4, "totals": {"EUR": "9.00", "USD": "17.75"}}

The lab download contains these files and sample data. Use a disposable directory and fictional inputs. Tests described here were run locally; no hosted CI or production deployment is implied.

Documentation