Python csv 模块

DictReader/DictWriter, the newline rule, encodings, and delimiter variants.

Beginner
Key PointsAlways open CSV files with `newline=""` — otherwise Windows inserts blank lines between rows.

Read

csv.reader yields lists; DictReader uses the first row as headers and yields dicts.

Python
import csv

with open("users.csv", encoding="utf-8", newline="") as f:
    for row in csv.DictReader(f):
        print(row["name"], row["age"])
Output
alice 30
bob 25

Write

DictWriter needs writeheader() first. extrasaction="ignore" tolerates extra keys.

Python
import csv

rows = [{"name": "alice", "age": 30}, {"name": "bob", "age": 25}]
with open("out.csv", "w", encoding="utf-8", newline="") as f:
    w = csv.DictWriter(f, fieldnames=["name", "age"])
    w.writeheader()
    w.writerows(rows)
print(open("out.csv", encoding="utf-8").read().strip())
Output
name,age
alice,30
bob,25

Variants

CSV is not just commas: Chinese Excel often exports GBK with semicolons. Be explicit.

Python
import csv

with open("export.csv", encoding="gbk", newline="") as f:
    reader = csv.reader(f, delimiter=";", quotechar='"')
    for row in reader:
        print(row[:3])
        break
ParameterDefaultChange when
delimiter,Semicolon exports
quotechar"Rarely
encodingplatformAlways set utf-8 / gbk
newline—Always ""
Chinese Excel garbles plain UTF-8 CSV; use encoding="utf-8-sig" to add a BOM.

Friends & Partners