Recipe 11.1 · Python
A Correct CSV Writer
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
CSV looks trivial, so everyone writes their own. Then a field contains a comma, a quote or a line break, and the file shifts columns from that row onward. Numbers are written with the server's culture, so a German server writes 1234,5. Excel opens a UTF-8 file as Windows-1252 and turns Müller into Müller. And a field that begins with = becomes a formula when someone opens the file in Excel, which is a known injection vector.
The way it's often written
Anti-pattern: shown so you can recognize it. Don't copy this one.
No quoting, culture-dependent numbers and dates, the whole file built in memory, and UTF-8 without a byte order mark, which Excel misreads.
Requirements: Python 3.12+. Standard library only, nothing to install.
"""CSV export built by string concatenation with no quoting or culture control
Source: ImproveCode, Chapter 11, Recipe 11.1 "A Correct CSV Writer"
Section: The way it's often written
Book page: 231 -- original C# listing
Converted from C# to Python.
ANTI-PATTERN: kept deliberately faithful to the C# 'not to copy' example; do not use.
DataTable rows -> list of dicts; StringBuilder -> list of strings joined.
Commas/quotes/newlines in data break the file; formulas are not neutralized.
"""
from collections.abc import Iterable, Mapping
from typing import Any
def export(rows: Iterable[Mapping[str, Any]], path: str) -> None:
sb: list[str] = []
for row in rows:
sb.append(str(row["Name"]) + "," + str(row["City"]) + "," +
str(row["Balance"]) + "," + str(row["Opened"]) + "\n")
with open(path, "w") as f:
f.write("".join(sb))
The improved recipe
The writer quotes fields only when needed, doubles embedded quotes, formats values with the invariant culture, neutralizes formula-like text, and streams rows to any TextWriter. Columns are defined once, with a header and a value selector, so the same definition can drive CSV and Excel output.
A usage snippet:
Requirements: Python 3.12+. Standard library only, nothing to install.
"""CSV writer with RFC 4180 quoting, invariant formatting and formula-injection guard
Source: ImproveCode, Chapter 11, Recipe 11.1 "A Correct CSV Writer"
Section: The improved recipe
Book page: 231-233 -- original C# listing
Converted from C# to Python.
Hand-written escaping kept (rather than the csv module) to preserve the
formula-protection rule; IFormattable format strings -> Python format specs;
UTF8Encoding(BOM) -> "utf-8-sig" when writing for Excel.
"""
from __future__ import annotations
import datetime as dt
from collections.abc import Callable, Iterable, Sequence
from dataclasses import dataclass
from decimal import Decimal
from typing import Any, Generic, TextIO, TypeVar
T = TypeVar("T")
_FORMULA_STARTS = ("=", "+", "-", "@", "\t", "\r")
@dataclass(frozen=True)
class ExportColumn(Generic[T]):
header: str
value: Callable[[T], Any]
format: str | None = None
class CsvWriter:
def __init__(self, writer: TextIO, delimiter: str = ",",
protect_formulas: bool = True) -> None:
if writer is None:
raise ValueError("writer is required")
self._writer = writer
self._delimiter = delimiter
self._protect_formulas = protect_formulas
@staticmethod
def create_file(path: str, for_excel: bool = True) -> TextIO:
return open(path, "w", encoding="utf-8-sig" if for_excel else "utf-8",
newline="")
async def write_row_async(self, fields: Iterable[str | None]) -> None:
line = self._delimiter.join(
CsvWriter.escape(f, self._delimiter, self._protect_formulas)
for f in fields)
self._writer.write(line + "\r\n")
async def write_records_async(
self, records: Iterable[T], columns: Sequence[ExportColumn[T]]
) -> None:
if records is None or columns is None:
raise ValueError("records and columns are required")
await self.write_row_async(c.header for c in columns)
for record in records:
await self.write_row_async(
CsvWriter.format_value(c.value(record), c.format)
for c in columns)
self._writer.flush()
@staticmethod
def format_value(value: Any, format: str | None) -> str:
match value:
case None:
return ""
case bool():
return "true" if value else "false"
case dt.datetime():
return value.strftime(format or "%Y-%m-%d %H:%M:%S")
case dt.date():
return value.strftime(format or "%Y-%m-%d")
case int() | float() | Decimal():
return format_number(value, format)
case _:
return str(value)
@staticmethod
def escape(field: str | None, delimiter: str = ",",
protect_formulas: bool = True) -> str:
if not field:
return ""
if (protect_formulas and field.startswith(_FORMULA_STARTS)
and not _is_float(field)):
field = "'" + field
must_quote = (delimiter in field or '"' in field or "\n" in field
or "\r" in field or field[0] == " " or field[-1] == " ")
return '"' + field.replace('"', '""') + '"' if must_quote else field
def format_number(value: int | float | Decimal, fmt: str | None) -> str:
"""Format a number invariantly; supports .NET-style "0.00" patterns."""
if fmt is None:
return str(value)
if set(fmt) <= set("0#.,"):
decimals = len(fmt.split(".", 1)[1]) if "." in fmt else 0
grouping = "," if "," in fmt.split(".")[0] else ""
return f"{value:{grouping}.{decimals}f}"
return format(value, fmt)
def _is_float(text: str) -> bool:
try:
float(text)
return True
except ValueError:
return False
Requirements: Python 3.12+. Standard library only, nothing to install.
"""Usage: export customers to CSV with typed column definitions
Source: ImproveCode, Chapter 11, Recipe 11.1 "A Correct CSV Writer"
Section: The improved recipe
Book page: 233 -- original C# listing
Converted from C# to Python.
Usage fragment wrapped in a function; CsvWriter/ExportColumn come from p231.
`await using` -> `with` on the file returned by create_file.
"""
from __future__ import annotations
from collections.abc import Iterable
from typing import Any
from p231_r11_1_csv_writer_quoting_formula_guard import CsvWriter, ExportColumn
async def export_customers(customers: Iterable[Any]) -> None:
columns: list[ExportColumn[Any]] = [
ExportColumn("Customer", lambda c: c.name),
ExportColumn("City", lambda c: c.city),
ExportColumn("Balance", lambda c: c.balance, "0.00"),
ExportColumn("Opened", lambda c: c.opened_on),
]
with CsvWriter.create_file(r"D:\exports\customers.csv") as file:
await CsvWriter(file).write_records_async(customers, columns)
How it works
The rules come from RFC 4180, the closest thing CSV has to a standard. A field is quoted when it contains the delimiter, a quote, or a line break, and embedded quotes are doubled: Say "hi" becomes "Say ""hi""". Fields with leading or trailing spaces are quoted too, because some readers trim unquoted whitespace. Rows end with CRLF, as the RFC specifies; every reader I know accepts it.
FormatValue uses the invariant culture for every number and date, so the file is the same on every server. Dates default to ISO 8601 (2025-06-30), which sorts correctly as text and which Excel and SQL Server both parse. Pass a format per column when a consumer needs something else.
Formula protection follows the OWASP advice for CSV injection: a text field that starts with =, +, -, @, a tab or a carriage return gets a leading apostrophe, so Excel shows it as text instead of evaluating it. Real numbers such as -42.5 are left alone. Turn protection off for files that go only to other programs, since the apostrophe becomes part of the data there.
CreateFile controls the byte order mark. With forExcel: true the file starts with the UTF-8 BOM, which is how Excel knows the file is UTF-8 when a user double-clicks it. Many Unix tools and some import programs treat the BOM as part of the first header, so pass false for machine-to-machine files.
Variations and pitfalls
- Semicolons for European Excel. Excel uses the list separator from the user's regional settings. For users in much of Europe that is
;. Pass';'as the delimiter, or give them an.xlsx(Recipe 11.3) and avoid the question. - Streaming to a web response. Wrap
Response.Bodyin aStreamWriterand write records as they come from the database. Memory stays flat for any size. - Atomic output. For files other systems pick up, write through
AtomicFile.WriteAsyncfrom Recipe 10.2. - CsvHelper. The
CsvHelperpackage is excellent and handles class mapping, type conversion and many dialects. I use this small writer when a project only needs to produce a few known files.