Recipe 11.2 · Python
A Correct CSV Reader
The Python listings are conversions of the book's C# code to Python 3.12. Each file's header says what it needs to run. The explanations were written for the C# version, so some names in the text refer to .NET.
Problem
The usual reader calls line.Split(','). That breaks on the first quoted field containing a comma, and ReadLine breaks on the first quoted field containing a line break. Import files from banks and partners have both. The resulting bugs are silent: values land in the wrong columns and get imported anyway.
The way it's often written
Anti-pattern: shown so you can recognize it. Don't copy this one.
"Smith, John" becomes two fields, decimal.Parse uses the server's culture, and the whole file is in memory.
Requirements: Python 3.12+. Standard library only, nothing to install.
"""CSV import that splits each line on commas and parses by position
Source: ImproveCode, Chapter 11, Recipe 11.2 "A Correct CSV Reader"
Section: The way it's often written
Book page: 234 -- original C# listing
Converted from C# to Python.
ANTI-PATTERN: kept deliberately faithful to the C# 'not to copy' example; do not use.
File.ReadAllLines().Skip(1) -> readlines()[1:]; decimal.Parse -> Decimal().
Breaks on quoted commas, embedded newlines and column reordering.
"""
from collections.abc import Callable
from dataclasses import dataclass
from decimal import Decimal
@dataclass
class Customer:
name: str = ""
balance: Decimal = Decimal(0)
def import_customers(path: str, save: Callable[[Customer], None]) -> None:
with open(path) as f:
lines = f.read().splitlines()
for line in lines[1:]:
parts = line.split(",")
c = Customer(
name=parts[0].strip('"'),
balance=Decimal(parts[2]),
)
save(c)
The improved recipe
A small state machine reads characters, tracks whether it is inside quotes, and yields one record at a time. A header-aware wrapper gives access by column name, so a partner adding a column does not break the import.
A usage snippet that parses with the invariant culture and collects errors per row:
Requirements: Python 3.12+. Standard library only, nothing to install.
"""Streaming CSV reader: quoted fields, embedded newlines, header lookup by name
Source: ImproveCode, Chapter 11, Recipe 11.2 "A Correct CSV Reader"
Section: The improved recipe
Book page: 235-237 -- original C# listing
Converted from C# to Python.
The hand-written state machine is kept (rather than the csv module) so the
line counting and field-length limit match the C#; TextReader.Peek is emulated
with a one-character look-ahead. InvalidDataException -> ValueError subclass.
"""
from __future__ import annotations
from collections.abc import Iterator, Mapping
from typing import TextIO
class InvalidDataError(ValueError):
"""Equivalent of System.IO.InvalidDataException."""
class _PeekReader:
def __init__(self, reader: TextIO) -> None:
self._reader = reader
self._next: str | None = None
def read(self) -> str:
if self._next is not None:
ch, self._next = self._next, None
return ch
return self._reader.read(1)
def peek(self) -> str:
if self._next is None:
self._next = self._reader.read(1)
return self._next
def read_records(
reader: TextIO, delimiter: str = ",", max_field_length: int = 1 << 20
) -> Iterator[list[str]]:
if reader is None:
raise ValueError("reader is required")
r = _PeekReader(reader)
fields: list[str] = []
field: list[str] = []
in_quotes = False
row_has_data = False
line = 1
while (ch := r.read()) != "":
if in_quotes:
if ch == '"':
if r.peek() == '"':
field.append('"')
r.read()
else:
in_quotes = False
else:
if ch == "\n":
line += 1
field.append(ch)
elif ch == '"' and len(field) == 0:
in_quotes = True
row_has_data = True
elif ch == delimiter:
fields.append("".join(field))
field.clear()
row_has_data = True
elif ch in ("\r", "\n"):
if ch == "\r" and r.peek() == "\n":
r.read()
line += 1
if row_has_data or len(field) > 0:
fields.append("".join(field))
yield list(fields)
fields.clear()
field.clear()
row_has_data = False
else:
field.append(ch)
row_has_data = True
if len(field) > max_field_length:
raise InvalidDataError(f"Field too long near line {line}.")
if in_quotes:
raise InvalidDataError(f"Unterminated quoted field near line {line}.")
if row_has_data or len(field) > 0:
fields.append("".join(field))
yield list(fields)
class CsvRow:
def __init__(self, row_number: int, fields: list[str],
index: Mapping[str, int]) -> None:
self.row_number = row_number
self._fields = fields
self._index = index
def has_column(self, name: str) -> bool:
return name.casefold() in self._index
def __getitem__(self, column: str) -> str | None:
i = self._index.get(column.casefold())
return self._fields[i] if i is not None and i < len(self._fields) else None
def read_with_header(reader: TextIO, delimiter: str = ",") -> Iterator[CsvRow]:
records = read_records(reader, delimiter)
header = next(records, None)
if header is None:
return
# Case-insensitive; first occurrence of a duplicate name wins.
index: dict[str, int] = {}
for i, name in enumerate(header):
index.setdefault(name.strip().casefold(), i)
row_number = 1
for record in records:
row_number += 1
yield CsvRow(row_number, record, index)
Requirements: Python 3.12+. Standard library only, nothing to install.
"""Usage: read a CSV with a header and collect per-row validation errors
Source: ImproveCode, Chapter 11, Recipe 11.2 "A Correct CSV Reader"
Section: The improved recipe
Book page: 237 -- original C# listing
Converted from C# to Python.
Usage fragment wrapped in a function; CsvReader comes from p235.
StreamReader(detectEncodingFromByteOrderMarks) -> encoding="utf-8-sig";
decimal.TryParse(Number, Invariant) -> Decimal() after removing group commas.
"""
from __future__ import annotations
from decimal import Decimal, InvalidOperation
from p235_r11_2_csv_reader_quoted_fields_header import read_with_header
def _try_parse_decimal(text: str | None) -> Decimal | None:
if text is None:
return None
try:
return Decimal(text.strip().replace(",", ""))
except InvalidOperation:
return None
def import_file(path: str, errors: list[str]) -> None:
with open(path, encoding="utf-8-sig", newline="") as reader:
for row in read_with_header(reader):
balance = _try_parse_decimal(row["Balance"])
if balance is None:
errors.append(f"Row {row.row_number}: Balance is not a number.")
continue
# ...
How it works
The reader keeps one piece of state that matters: whether it is inside a quoted field. Inside quotes, delimiters and line breaks are data, and a doubled quote is one literal quote. Outside quotes, a delimiter ends a field and a line break ends a record. CRLF, LF and lone CR line endings all work, so files from Windows, Unix and old Mac exports read the same. Blank lines are skipped.
Records are yielded one at a time from a TextReader, so a 2 GB file is read with a few kilobytes of memory. StreamReader buffers internally, which keeps the per-character Read calls cheap. With detectEncodingFromByteOrderMarks: true it also removes the BOM that the writer in Recipe 11.1 adds for Excel, so the first header is Customer, not \uFEFFCustomer.
Two checks protect the import from broken or hostile input. An unterminated quote throws with an approximate line number instead of silently swallowing the rest of the file into one field. And a field longer than one million characters throws, so a missing quote cannot build a gigabyte string.
ReadWithHeader maps header names to positions, ignoring case and surrounding spaces. Code asks for row["Balance"], and the import keeps working when a partner reorders columns or adds new ones. A missing column returns null, which your validation reports. RowNumber counts records, with the header as row 1; that matches what users see in Excel unless fields contain line breaks.
The round trip is the test that matters: anything the writer produces, the reader returns unchanged. I keep that as a unit test with commas, quotes, line breaks, leading spaces and non-Latin text in the fields.
Variations and pitfalls
- Parse with the invariant culture. The reader returns strings. Use
CultureInfo.InvariantCulturefor numbers andDateOnly.TryParseExactwith the formats the partner specified. - Unknown encodings. Old files from Windows systems may be Windows-1252, not UTF-8. On modern .NET, call
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance)once beforeEncoding.GetEncoding(1252)will work. Agree on UTF-8 for new feeds. - Bulk loading. For large imports, feed parsed rows into
SqlBulkCopy(Chapter 1) instead of inserting row by row. - Validate rows, not files. Collect errors per row with the row number, and decide up front whether one bad row rejects the file or is written to a rejects file.