Most people who search for a Python script to process a CSV file get the same answer: open the file, loop over csv.reader, split on commas, cast the third column to float. That example works on the sample file that ships with the tutorial. It fails on the first real export from a European bank, an accounting package or Excel running with a Portuguese, Spanish or German locale, because those files use a semicolon as the delimiter, a comma as the decimal mark and a day-first date.
Engineers who move to Lisbon or Porto tend to meet this in their first month. A finance or operations colleague sends a file called extrato.csv, the quick script prints a traceback on row 1, and the fix is rarely a one-liner. This memo shows the version most of us write first, the version that holds up, and the cases where you should not write either.
The decision this memo asks for
The question is narrow: for recurring CSV files that arrive from people and systems you do not control, should the team keep a small standard-library script, move to pandas, or load everything into a query engine such as DuckDB? The recommendation, argued in the sections below, is a standard-library script of roughly 120 lines for files under about 2 GB that arrive weekly or daily, with a strict contract about what it accepts and a rejects file for everything else.
Three terms carry the argument, so here they are in one place.
Dialect: the set of formatting choices a CSV file makes, including delimiter, quote character, escape rules and line terminator. Python's csv module models this explicitly, and csv.Sniffer can guess it from a sample.
BOM (byte order mark): three bytes, EF BB BF, that some tools write at the start of a UTF-8 file. Excel's "CSV UTF-8" save option adds them. If you open the file as plain utf-8, the first header becomes "Data" and every lookup by column name fails.
Rejects file: a second output that receives every row the script could not parse, with the original values and a reason. It turns silent data loss into a list someone can fix.
The memo is written for a team of 2 to 8 engineers supporting finance, payroll or operations staff. A data platform team with a warehouse and an ingestion tool should read the last section first, because for them the answer is usually a loader they already own.
Before: the script almost everyone writes first
Here is a typical first attempt, close to what appears in many tutorials.
import csv
total = 0.0
with open("extrato.csv") as f:
reader = csv.reader(f)
next(reader)
for row in reader:
total += float(row[2])
print(total)
It has five problems, and each one produces a different failure on a Portuguese export.
The file is opened without an encoding, so Python uses the platform default. On a Linux container that is UTF-8, on an older Windows laptop it can be cp1252, and the same script behaves differently on two machines. The file is opened without newline="", which the csv module documentation asks for, so quoted fields containing line breaks can be split incorrectly.
The reader assumes a comma, so a semicolon file arrives as one long string per row and row[2] raises IndexError. The amount "1.234,56" cannot be passed to float at all. Finally, a single bad row stops the whole run, which means a 40,000-row file with one stray line produces nothing.
The deeper issue is that the script has no contract. It does not say which columns it expects, which formats it accepts or what happens to rows that do not fit. When it breaks, nobody knows whether the file is wrong or the code is, and the person who sent the file has no way to check it before sending the next one.
That is the state most teams are in when someone finally asks for a proper version. The "after" script below keeps the standard library only, so it runs anywhere Python 3.9 or newer is installed, including the locked-down laptops finance teams often use.
After: a script that knows what it accepts
The rewritten version separates four jobs: detect the encoding, detect the dialect, parse each row against an explicit schema, and write clean rows and rejected rows to separate files.
#!/usr/bin/env python3
"""Normalise a European-locale CSV export into UTF-8, ISO dates and dot decimals."""
import codecs
import csv
import logging
import sys
from datetime import datetime
from decimal import Decimal, InvalidOperation
from pathlib import Path
ENCODINGS = ("utf-8-sig", "cp1252")
COLUMNS = {"data": "date", "descricao": "description", "montante": "amount", "nif": "tax_id"}
def detect_encoding(path):
sample = path.open("rb").read(65536)
for enc in ENCODINGS:
try:
codecs.getincrementaldecoder(enc)().decode(sample, final=False)
return enc
except UnicodeDecodeError:
continue
raise ValueError(f"cannot decode {path}")
def norm_header(name):
table = str.maketrans("áàãâéêíóõôúç", "aaaaeeiooouc")
return name.strip().lower().translate(table)
def parse_amount(text):
s = text.strip().replace(" ", "").replace(" ", "").replace("€", "")
if "," in s:
s = s.replace(".", "").replace(",", ".")
return Decimal(s)
def parse_date(text):
for fmt in ("%d/%m/%Y", "%d-%m-%Y", "%Y-%m-%d"):
try:
return datetime.strptime(text.strip(), fmt).date().isoformat()
except ValueError:
pass
raise ValueError(f"bad date {text!r}")
def parse_row(raw):
tax_id = "".join(raw["tax_id"].split())
if not (tax_id.isdigit() and len(tax_id) == 9):
raise ValueError(f"bad NIF {tax_id!r}")
return {
"date": parse_date(raw["date"]),
"description": " ".join(raw["description"].split()),
"amount": str(parse_amount(raw["amount"])),
"tax_id": tax_id,
}
def process(src, dst, rej):
enc = detect_encoding(src)
ok = bad = 0
with src.open(encoding=enc, newline="") as f:
dialect = csv.Sniffer().sniff(f.read(8192), delimiters=";,\t")
f.seek(0)
reader = csv.DictReader(f, dialect=dialect)
mapping = {h: COLUMNS[norm_header(h)] for h in reader.fieldnames if norm_header(h) in COLUMNS}
missing = set(COLUMNS.values()) - set(mapping.values())
if missing:
raise SystemExit(f"missing columns: {sorted(missing)}")
with dst.open("w", encoding="utf-8", newline="") as out, rej.open("w", encoding="utf-8", newline="") as bad_out:
w = csv.DictWriter(out, fieldnames=list(COLUMNS.values()))
wr = csv.DictWriter(bad_out, fieldnames=["line", "reason", "raw"])
w.writeheader()
wr.writeheader()
for row in reader:
raw = {mapping[k]: (v or "") for k, v in row.items() if k in mapping}
try:
w.writerow(parse_row(raw))
ok += 1
except (ValueError, InvalidOperation, KeyError) as exc:
wr.writerow({"line": reader.line_num, "reason": str(exc), "raw": repr(row)})
bad += 1
logging.info("%s: encoding=%s delimiter=%r ok=%d rejected=%d", src.name, enc, dialect.delimiter, ok, bad)
return ok, bad
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(message)s")
ok, bad = process(Path(sys.argv[1]), Path(sys.argv[2]), Path(sys.argv[3]))
sys.exit(0 if bad == 0 else 2)
A few choices deserve a sentence each. The encoding check tries utf-8-sig first because it accepts plain UTF-8 too and silently drops the BOM; cp1252 comes second because it decodes almost any byte sequence and would hide a real UTF-8 file if it went first. The incremental decoder with final=False avoids a false failure when the 64 KB sample cuts a multi-byte character in half.
Money goes through Decimal and leaves as a string, so 0.1 plus 0.2 stays 0.3 in the output. The NIF check is deliberately simple, nine digits, and does not validate the control digit; add that only if the downstream system needs it. The exit code is 2 when any row was rejected, which lets a cron job or CI step flag the run without treating it as a crash.
What the script refuses to do matters as much. It does not guess a column by position, so a reordered export still works and a renamed one stops with a clear message listing the missing names. It does not fix amounts it cannot read; it records them.
It does not deduplicate, because two identical transfers of 1.200,00 euros on the same day can both be real, and that decision belongs to the person reconciling, not to a parser. On a 900-row monthly file it finishes in well under a second, and on a 1.5 GB file it streams row by row with flat memory use, since nothing except the current row is held in memory.
Step by step: running it on a real export
The order matters more than the code. This is the procedure that has worked for monthly bank and payroll files.
- Ask for three sample files from three different months before writing anything. Formats drift: a bank adds a "Saldo" column in March, an accountant switches from "CSV (separado por ponto e vírgula)" to "CSV UTF-8" in June.
- Open each sample in a hex viewer or with
head -c 3 file | xxdand check the first bytes. EF BB BF means a BOM is present. - Write the column mapping as data, the COLUMNS dictionary above, and agree it with the person who sends the file. Every header you accept is part of the contract.
- Run the script on all three samples. Expect rejects on the first pass; that is the point of the rejects file.
- Read every rejected row. Classify each one as a file problem (send it back), a parser gap (fix the code) or a legitimate edge case (add a rule and a test).
- Add one test per edge case with a three-line CSV fixture. Ten fixtures cover most of what a Portuguese bank export will throw at you.
- Schedule the run and alert on exit code 2, and also on a row count that differs from the previous month by more than 30%.
- Keep the original files for at least as long as finance keeps its records, which in Portugal tends to mean years rather than months, so you can rerun any month after a parser change.
Step 7 catches the failure the rejects file cannot: a file that parses perfectly but contains half the expected rows because the export was cut at a page limit.
Mini-case: a payroll reconciliation in Lisbon
This case is illustrative, built from patterns that come up repeatedly rather than from one company.
A 60-person software company in Lisbon reconciles salary transfers every month. The payroll provider sends a CSV with 60 rows, the bank sends an export with about 900 movements, and an operations analyst matches them by NIF and amount in a spreadsheet. It takes her roughly 4 hours each month.
The first script attempt used the "before" pattern and failed immediately on the bank file: semicolons, cp1252 encoding, amounts like "-2.150,00". After the rewrite, the first run on the June file produced 58 matched rows and 2 rejects.
One reject was a NIF typed with spaces in the middle, the way people write it on invoices, so the parser now removes all internal whitespace before checking it. The other was a genuine error: a transfer of 2.150,00 euros where payroll said 2.105,00. That was a typo in the payroll system, found on day 1 instead of at the next audit.
Over the following 6 months the script ran on 6 files, rejected 9 rows in total and needed 2 code changes, both triggered by a new column the bank added. The analyst's monthly time dropped from about 4 hours to about 20 minutes, most of it spent reading the rejects file. At an internal cost of roughly 35 euros per hour, that is around 1,500 euros a year saved, against about 2 days of engineering time to build and test the script.
The number that mattered to the finance lead was different: the transfer error would previously have surfaced in a quarterly review, 2 to 3 months later.
Options considered: csv module, pandas or DuckDB
The standard library is not the only reasonable choice, and the memo should show what was rejected and why.
| Option | Strength | Weakness | Fits when |
|---|---|---|---|
| csv module script | No dependencies, row-level control, streams files of any size | More code for joins and aggregates | Recurring files under about 2 GB, strict validation, locked-down machines |
| pandas | read_csv handles sep, decimal, thousands and dayfirst in one call | Whole file in memory by default, type guessing hides bad rows | Exploration, one-off analysis, files that fit comfortably in RAM |
| DuckDB | SQL over CSV, very fast on large files, good type detection | Another dependency, row-level reject handling needs extra work | Files of several GB, analytics queries, joins across many exports |
| Spreadsheet macro | Finance staff can maintain it | Hard to test, breaks quietly, versioning is weak | Fewer than 5 files a year, no downstream system |
pandas deserves a fair hearing, because pd.read_csv(path, sep=";", decimal=",", thousands=".", encoding="utf-8-sig") does in one line what the script does in twenty. The problem is what happens to the row that does not fit. By default pandas will often turn a bad amount into a column of strings, or a bad date into NaT, and the run succeeds. For reconciliation work, a run that succeeds with wrong data is worse than one that stops.
DuckDB wins on raw size. Its CSV reader can scan a 5 GB export in seconds on a laptop and lets you write the matching logic as a SQL join. If the files grow past the point where a nightly Python run takes more than a few minutes, that is the moment to switch.
When not to write this script at all
A custom parser is a maintenance commitment, and there are clear cases where it is the wrong move.
Do not write it for a one-off file. If someone needs a total from a single export, open it in a spreadsheet with the correct locale import settings, or run one pandas line in a notebook. Twenty minutes of manual checking beats two days of building something that will never run again.
Do not write it when the source system offers a structured export. Many Portuguese banks and accounting tools can export SAF-T PT files, OFX or an API feed. Those formats carry types and schemas, and parsing them is usually more reliable than reverse-engineering a CSV built for human eyes.
Do not write it when your company already has an ingestion tool or a warehouse with a CSV loader and a data team that owns it. A side script that duplicates their pipeline creates two versions of the truth, and the finance team will eventually ask why the numbers differ by 0.4%.
Do not write it if nobody will read the rejects file. The rejects file is the reason the "after" version exists. If it goes to a folder no human opens, you have rebuilt the silent failure of the first script with more lines of code. In that situation, either assign an owner for the rejects before writing a single line, or keep the spreadsheet and the manual check that at least someone looks at every month, all 12 months of the year.