Two good answers: the built-in csv module (zero dependencies) or pandas (if you're analyzing). Both below, plus the errors that actually happen.
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"])
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])
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.
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)
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().
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.