import csv
header = ['class', 'id']
# --列表型写入
rows = [
[1, 2],
[3, 4]
]
with open('demo.csv', 'w') as f:
f_csv = csv.writer(f) # csv 写对象
f_csv.writerow(header) # 写入单行
f_csv.writerows(rows) # 写入多行
# --字典型写入
rows = [
{
'class': 1, 'id': 2},
...
]
with open('test.csv', 'w') as f:
f_csv = csv.DictWriter(f, header)
f_csv.writeheader()
f_csv.writerows(rows)
#------------读取
with open('test.csv', 'r') as f:
# 列表类型读取
f_csv = csv.reader(f)
for i in f_csv:
i # 列表
# 字典类型读取
f_csv = csv.DictReader(f)
for i in f_csv:
i # 字典