csv
cheat sheet
Python’s csv module at a glance: reader and DictReader, writer and DictWriter, dialects, quoting, delimiters, sniffing, encodings and everyday recipes.
- Version
- v3.15.2
- Snippets
- 56
- Sections
- 8
Version notes · csv 3.15.2
- 3.15 opens files as UTF-8 by default (PEP 686). Excel files with a BOM still need
encoding="utf-8-sig". - 3.15 makes
Sniffer.sniff()delimiter detection up to 1.6× faster. - 3.13 / 3.12 added
QUOTE_STRINGSandQUOTE_NOTNULLquoting modes. - Every value you read is a
str. Convert types yourself, or use pandas / Polars for typed data.
The standard library’s CSV parser and writer: it handles quoting, embedded commas and newlines, and the quirks of Excel, so you never split(",") by hand.
Stdlib
nothing to install
Streaming
row by row, any file size
Correct quoting
commas, quotes, newlines
Strings only
you convert the types
Quick start
import csvwith open("people.csv", newline="") as f: rows = list(csv.DictReader(f))adults = [r for r in rows if int(r["age"]) >= 18]with open("adults.csv", "w", newline="") as f: w = csv.DictWriter(f, fieldnames=["name", "age"], extrasaction="ignore") w.writeheader() w.writerows(adults)- Always open with
newline="" - Each row is a
list[str] - Take the header row
- Each row is a
dictkeyed by header - File has no header row
- Header names (after the first read)
- Extra / missing values per row
- Source line (for error messages)
- Excel UTF-8 with a BOM
- Old Windows / Excel exports
Without newline="", quoted fields that contain line breaks are read wrong, and \r\n endings can show up as blank rows on Windows.
- Open for writing
- List-based writer
- One row
- Many rows
- Dict-based writer
- Write the header row
- Skip keys not in
fieldnames - Value for missing keys
- Append to an existing file
- So Excel shows UTF-8 correctly
- Semicolon CSV
- TSV (or
dialect="excel-tab") - Custom delimiter and quote
- Ignore spaces after the delimiter
- Backslash escapes
- Unix line endings (default
\r\n) \nendings, quote everything- Name your own dialect
excel,excel-tab,unix…- Raise
csv.Erroron bad input
- Only fields that need it (default)
- Every field
- All non-numbers; reader turns unquoted into
float - Only strings; reader: unquoted →
float, empty →None - Everything but
None; reader: empty unquoted →None - Nothing (needs
escapecharfor delimiters)
A quote inside a quoted field is doubled: "say ""hi""". Set doublequote=False + escapechar for \" style.
- Read a sample, rewind
- Guess delimiter and quoting
- Only consider these delimiters
- Does it look like a header row?
- Read with the guessed dialect
- What it found
- Parse a string
- Any iterable of lines works
- Build CSV text
- From a binary stream (zip, HTTP)
- Allow fields over 128 KiB
- Convert types
- Filter while copying
- Sum per key (with
defaultdict(float)) - Drop duplicate ids
- Header from the first dict
- Sort rows
Need joins, typed columns or speed on big files? pl.read_csv() (Polars) or pd.read_csv() (pandas) are one line.
- Malformed CSV
- Report where
- Wrong
encoding=: tryutf-8-sigorcp1252
Messages
- Raise
csv.field_size_limit() - Use
extrasaction="ignore" - Open with
newline=""
