Python csv 模块
DictReader/DictWriter, the newline rule, encodings, and delimiter variants.
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 25Write
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,25Variants
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| Parameter | Default | Change when |
|---|---|---|
| delimiter | , | Semicolon exports |
| quotechar | " | Rarely |
| encoding | platform | Always set utf-8 / gbk |
| newline | — | Always "" |
Chinese Excel garbles plain UTF-8 CSV; use
encoding="utf-8-sig" to add a BOM.读取
csv.reader 按位置返回列表,csv.DictReader 用首行做表头返回字典。后者可读性高得多,代价是不能有重复列名。
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写入
DictWriter 需要先 writeheader()。传 extrasaction="ignore" 可以让多出来的键不报错。
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变体
CSV 不是只有逗号:Excel 在中文环境常导出 GBK 编码、分号分隔的文件。参数都要显式指定。
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| 参数 | 默认 | 何时改 |
|---|---|---|
| delimiter | , | 分号导出 |
| quotechar | " | 很少需要 |
| encoding | 平台默认 | 总是显式写 utf-8 / gbk |
| newline | — | 总是 "" |
中文 Excel 打开 UTF-8 CSV 可能乱码,加 BOM 可解:
encoding="utf-8-sig"。