How to read a CSV file in Python

Two good answers: the built-in csv module (zero dependencies) or pandas (if you're analyzing). Both below, plus the errors that actually happen.

No dependencies: csv.DictReader (usually what you want)

Each row arrives as a dict keyed by the header row — readable code, no index counting.

import csv

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

# row = {"name": "Ada", "email": "[email protected]", ...} per line
# values are ALWAYS strings — convert numbers yourself:
        total += float(row["amount"])

No header row? Plain reader + skip patterns

with open("data.csv", newline="", encoding="utf-8") as f:
    reader = csv.reader(f)          # rows as plain lists
    next(reader)                    # ← skip the header line if needed
    for row in reader:
        print(row[0], row[2])

With pandas (for analysis)

import pandas as pd

df = pd.read_csv("users.csv")
df.head()                          # peek at first 5 rows
df["amount"].sum()                # columns come typed already

# common knobs:
pd.read_csv("f.csv", sep=";")              # semicolon files (Europe!)
pd.read_csv("f.csv", skiprows=2)           # junk lines above header
pd.read_csv("f.csv", usecols=["name","amount"])  # only some columns

Which one? Reading rows to feed into your program → csv module, no install. Filtering/grouping/math on columns → pandas earns its 100MB.

Writing a CSV back out

rows = [{"name": "Ada", "score": 95}, {"name": "Lin", "score": 88}]

with open("out.csv", "w", newline="", encoding="utf-8") as f:
    w = csv.DictWriter(f, fieldnames=["name", "score"])
    w.writeheader()
    w.writerows(rows)
You will hit this (Windows)
UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d — a UTF-8 file opened without encoding="utf-8". And Excel-exported files are sometimes encoding="utf-8-sig" (the invisible BOM makes your first column name "name" — if row["name"] mysteriously KeyErrors, that's why). Also: blank lines between rows on Windows = you forgot newline="" in open().
Don't do it by hand
line.split(",") works until the first value containing a comma — "Smith, John",42 — then silently corrupts your data. Quoted fields are exactly why the csv module exists. Never split-parse a real CSV.
📚 This is one page of our Python series. The full crash course (with audio for your commute): Python in 10 Minutes →