Skip to main content
Files

How to read a CSV file in Python

Quick answer

Open the file with a with-block and use csv.reader for lists or csv.DictReader for dicts. Always pass encoding='utf-8'.

import csv

with open("data.csv", encoding="utf-8") as f:
    reader = csv.DictReader(f)
    for row in reader:
        print(row["name"], row["age"])

csv.DictReader reads the first row as headers and yields one dict per row, keyed by header name. This is safer than csv.reader (which yields plain lists) because column-order changes don't break your code.

The with-block guarantees the file is closed even if a row raises an exception. Always pass encoding='utf-8' explicitly β€” the platform default is Windows-1252 on Windows and utf-8 on macOS/Linux, which is a classic 'works on my machine' footgun.

For files over a few hundred MB, reach for pandas.read_csv() β€” it uses a C parser that's 5-10x faster.

Variations

csv.reader (lists, not dicts)

with open("data.csv", encoding="utf-8") as f:
    for row in csv.reader(f):
        print(row)  # ['Alice', '30', 'Berlin']

Use when the CSV has no header row.

Custom delimiter (TSV, pipe-separated)

with open("data.tsv", encoding="utf-8") as f:
    reader = csv.reader(f, delimiter="\t")

Also accepts quotechar= for non-standard quoting.

Large file β†’ pandas

import pandas as pd
df = pd.read_csv("data.csv")

Requires pip install pandas. 5-10x faster on files > 100MB.

Practise this in your browser

Every how-to has a live lesson. Free tier, no card.

Start free β†’

Unlock every lesson

Pro β€” $12/mo, unlimited AI, cancel any time.

See Pro plans β†’

Get one Python lesson + one career idea every Friday

No spam, no "buy our course now". Three bullets, every Friday. Unsubscribe with one click.

Related how-tos