On this page
  1. csv
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Reading & Writing UTF-8 CSV Files Properly (newline="")
  7. 2. Reading Tab-Separated Files (TSV)
  8. Gotchas & Boundaries
  9. Common Functions
  10. Classes & Objects
  11. Constants & Attributes

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

Common Functions

Classes & Objects

Constants & Attributes

Linked from

Related notes