On this page
csv
Prev: copyreg | Up: stdlib_module | Next: ctypes
Rel: configparser, tomllib, netrc, plistlib
Ref: docs.python.org — csv
Tags: #public #python3 #stdlib
Import
import csv
Overview
Reader and writer for comma- and tab-separated tabular text files (RFC 4180 dialects, quoting, and escaping). Prefer csv.DictReader and csv.DictWriter for self-documenting column-by-name access over positional row indexing.
Quick Start
import csv
import io
buf = io.StringIO()
writer = csv.DictWriter(buf, fieldnames=["name", "score"])
writer.writeheader()
writer.writerow({"name": "Ada", "score": 98})
buf.seek(0)
rows = list(csv.DictReader(buf))
assert rows == [{"name": "Ada", "score": "98"}]
Implementation Walkthrough
1. Reading & Writing UTF-8 CSV Files Properly (newline="")
Always pass newline="" to open() so the csv module—not Python's universal newline layer—handles embedded line breaks inside quoted fields:
import csv
from pathlib import Path
def write_records(path: Path, rows: list[dict[str, object]], fields: list[str]) -> None:
with path.open("w", encoding="utf-8", newline="") as fh:
writer = csv.DictWriter(fh, fieldnames=fields, extrasaction="ignore")
writer.writeheader()
writer.writerows(rows)
def read_records(path: Path) -> list[dict[str, str]]:
with path.open("r", encoding="utf-8", newline="") as fh:
return list(csv.DictReader(fh))
2. Reading Tab-Separated Files (TSV)
import csv
with open("data.tsv", "r", encoding="utf-8", newline="") as fh:
reader = csv.DictReader(fh, delimiter="\t")
Gotchas & Boundaries
- Always pass
newline=""toopen(): Omitting it inserts extra blank lines between every row on Windows and corrupts multi-line quoted cells. - All values read back as
str:csvhas no type system; convert integers, floats, and dates explicitly when reading. - Watch for UTF-8 BOM from Excel exports: Use
encoding="utf-8-sig"when reading CSVs generated by Excel so the first column name doesn't start with\ufeff. - Default field size limit is 128 KiB: Raise with
csv.field_size_limit(...)only if you intentionally process trusted wide fields.
Common Functions
- csv.field_size_limit() —
field_size_limit(...)— Sets an upper limit on parsed fields. - csv.get_dialect() —
get_dialect(name)— Return the dialect instance associated with name. - csv.list_dialects() —
list_dialects()— Return a list of all known dialect names. - csv.reader() —
reader(iterable, /, dialect='excel', **fmtparams)— Return a reader object that will process lines from the given iterable. - csv.register_dialect() —
register_dialect(name, /, dialect='excel', **fmtparams)— Create a mapping from a string name to a CVS dialect. - csv.unregister_dialect() —
unregister_dialect(name)— Delete the name/dialect mapping associated with a string name. - csv.writer() —
writer(fileobj, /, dialect='excel', **fmtparams)— Return a writer object that will write user data on the given file object.
Classes & Objects
- csv.Dialect — Describe a CSV dialect.
- csv.DictReader —
csv.DictReaderclass. (Methods:.fieldnames()) - csv.DictWriter —
csv.DictWriterclass. (Methods:.writeheader(),.writerow(),.writerows()) - csv.Error —
csv.Errorclass. (Methods:.add_note(),.with_traceback()) - csv.excel — Describe the usual properties of Excel-generated CSV files.
- csv.excel_tab — Describe the usual properties of Excel-generated TAB-delimited files.
- csv.Sniffer — "Sniffs" the format of a CSV file (i.e. delimiter, quotechar) Returns a Dialect object. (Methods:
.has_header(),.sniff()) - csv.unix_dialect — Describe the usual properties of Unix-generated CSV files.
Constants & Attributes
csv.QUOTE_ALL(int) =1csv.QUOTE_MINIMAL(int) =0csv.QUOTE_NONE(int) =3csv.QUOTE_NONNUMERIC(int) =2csv.QUOTE_NOTNULL(int) =5csv.QUOTE_STRINGS(int) =4
Linked from
- tuts/python3
- tuts/python3/stdlib_module
- tuts/python3/stdlib_module/configparser
- tuts/python3/stdlib_module/copyreg
- tuts/python3/stdlib_module/csv/Dialect
- tuts/python3/stdlib_module/csv/DictReader
- tuts/python3/stdlib_module/csv/DictWriter
- tuts/python3/stdlib_module/csv/Error
- tuts/python3/stdlib_module/csv/excel
- tuts/python3/stdlib_module/csv/excel_tab
- tuts/python3/stdlib_module/csv/field_size_limit
- tuts/python3/stdlib_module/csv/get_dialect
- tuts/python3/stdlib_module/csv/list_dialects
- tuts/python3/stdlib_module/csv/reader
- tuts/python3/stdlib_module/csv/register_dialect
- tuts/python3/stdlib_module/csv/Sniffer
- tuts/python3/stdlib_module/csv/unix_dialect
- tuts/python3/stdlib_module/csv/unregister_dialect
- tuts/python3/stdlib_module/csv/writer
- tuts/python3/stdlib_module/ctypes
- tuts/python3/stdlib_module/json
- tuts/python3/stdlib_module/netrc
- tuts/python3/stdlib_module/plistlib
- tuts/python3/stdlib_module/stdlib_module
- tuts/python3/stdlib_module/tomllib
- tuts/python3/tutorials/popular_application_domains/data_science_and_machine_learning
Related notes
- tuts/python3/stdlib_module/configparser Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/copyreg Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/csv/Dialect Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/csv/DictReader Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/csv/DictWriter Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/csv/Error Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/csv/excel Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/csv/excel_tab Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/csv/field_size_limit Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/csv/get_dialect Linked here; links to this page; shared tags: #stdlib