Skip to content

How to Parse CSV in Python: csv, pandas, and the Edge Cases That Bite

By DevToolSite Editorial

CSV looks like the simplest format in the world: rows, commas, done. Then a user uploads a file exported from Excel in Germany, and suddenly your parser is splitting on the wrong character, choking on a semicolon, or turning 00123 into 123. This guide walks through parsing CSV in Python properly — from the standard library to pandas — and covers the edge cases that actually show up in production.

If you just need to convert a file once, skip the code entirely and use the CSV to JSON converter — it detects delimiters and headers in your browser, and nothing is uploaded.

The standard library: csv.reader

Python ships with a battle-tested CSV parser. For most scripts, this is all you need:

import csv

with open("users.csv", newline="", encoding="utf-8") as f:
    reader = csv.reader(f)
    header = next(reader)
    for row in reader:
        record = dict(zip(header, row))
        print(record["email"])

Two details matter more than they look:

  • newline="" is not optional. The csv module handles line endings itself. Without it, fields containing embedded newlines (perfectly legal inside quotes) can be split incorrectly on Windows.
  • Every value is a string. csv.reader never guesses types. "42" stays "42", which is exactly what you want for ZIP codes, phone numbers, and IDs with leading zeros.

DictReader skips the zip dance

with open("users.csv", newline="", encoding="utf-8") as f:
    for record in csv.DictReader(f):
        print(record["name"], record["email"])

DictReader uses the first row as keys. If the file has no header, pass fieldnames=["id", "name", "email"] explicitly. Rows with extra columns land under a None key (or restkey if you set one) — a cheap way to detect malformed input instead of silently dropping data.

Dialects: when the delimiter isn’t a comma

“CSV” in the wild includes tab-separated (.tsv), semicolon-separated (most of continental Europe’s Excel exports), and pipe-separated files. The csv module handles all of them via dialect parameters:

reader = csv.reader(f, delimiter=";")          # European Excel
reader = csv.reader(f, delimiter="\t")         # TSV
reader = csv.register_dialect("pipes", delimiter="|", quoting=csv.QUOTE_MINIMAL)

Not sure what you’re dealing with? csv.Sniffer guesses from a sample:

with open("mystery.csv", newline="", encoding="utf-8") as f:
    sample = f.read(4096)
    dialect = csv.Sniffer().sniff(sample, delimiters=",;\t|")
    f.seek(0)
    reader = csv.reader(f, dialect)

Sniffer is a heuristic, not a guarantee — it can misfire on files with few columns or unusual quoting. For one-off inspection, paste the first lines into the CSV to JSON tool and check whether the detected delimiter produces sensible columns before committing to it in code.

pandas: when you want a dataframe, not rows

If the next step is analysis, grouping, or joining, pandas.read_csv saves a lot of boilerplate:

import pandas as pd

df = pd.read_csv(
    "sales.csv",
    dtype={"order_id": str, "zip": str},   # protect leading zeros
    parse_dates=["created_at"],
    na_values=["", "NULL", "N/A"],
)

The three arguments above prevent the three most common pandas CSV bugs:

  1. Type inference destroying identifiers. pandas happily converts 00123 to 123 and mixed columns to object. Pin critical columns with dtype=str.
  2. Dates staying as strings. parse_dates converts on load; add dayfirst=True for 31/12/2026-style dates.
  3. Sentinel nulls. Real exports use NULL, N/A, -, or empty strings. Normalize them with na_values so .isna() actually works.

For European files: pd.read_csv("export.csv", sep=";", decimal=","). Note that decimal="," only applies to unquoted numeric parsing — another reason to inspect a sample first.

Files too big for memory

Both the csv module and pandas can stream:

# Standard library: constant memory, one row at a time
with open("huge.csv", newline="", encoding="utf-8") as f:
    for row in csv.reader(f):
        process(row)

# pandas: chunked dataframes
for chunk in pd.read_csv("huge.csv", chunksize=100_000):
    process(chunk)

Streaming with csv.reader handles multi-gigabyte files on a laptop. Reach for chunked pandas only when you need vectorized operations per chunk; otherwise the standard library is faster to start and uses less memory.

Encodings: the Excel problem

Excel on Windows frequently saves “CSV” as Windows-1252 or with a UTF-8 BOM. Symptoms: UnicodeDecodeError, or a first column named \ufeffid.

# UTF-8 with BOM tolerance
with open("excel.csv", newline="", encoding="utf-8-sig") as f:
    ...

# Legacy Windows export
with open("legacy.csv", newline="", encoding="cp1252") as f:
    ...

utf-8-sig reads plain UTF-8 fine too, so it’s a safe default for user uploads. Never use errors="ignore" to make the error go away — you’ll silently corrupt names and addresses.

Malformed rows: fail loudly, early

Unclosed quotes are the classic malformed CSV. The csv module is lenient by default and will happily swallow the rest of the file into one field. Turn on strict mode when correctness matters:

reader = csv.reader(f, strict=True)   # raises csv.Error on bad quoting

Wrap iteration in a try/except and report the line number (reader.line_num) so the user can fix their file. A validator that says “unclosed quote on line 4,812” beats one that returns garbage.

Round-tripping: writing CSV back out

with open("out.csv", "w", newline="", encoding="utf-8") as f:
    writer = csv.writer(f, quoting=csv.QUOTE_MINIMAL)
    writer.writerow(["id", "name", "note"])
    writer.writerows(rows)

The writer quotes fields containing the delimiter, quotes, or newlines automatically — never build CSV lines with ",".join() or f-strings. If you need JSON on the other side, the JSON to CSV converter handles the reverse direction with proper quoting too.

Checklist

  • newline="" + explicit encoding on every open()
  • Strings by default; convert types deliberately
  • Detect or configure the delimiter — don’t assume comma
  • utf-8-sig for user uploads, cp1252 for legacy Excel
  • Stream large files; chunk pandas only when needed
  • strict=True when you’d rather fail than corrupt

Master these six habits and CSV stops being a source of 2 a.m. data bugs.

Advertisement
Ad slot · blog-in-article
#python#csv#data