-
数据以元组形式包裹
import csv
header=['name', 'age']
rows=[('a', '18'),('b', 19)]
with open('test.csv', 'w', newline='') as f:
w = csv.writer(f)
w.writerow(header)
w.writerows(rows)
-
数据是字典格式
import csv
header = ['name', 'age']
datas = [{'name': 'a', 'age': 15},
{'name': 'b', 'age': 18}
]
with open('test.csv', 'w', newline='') as f: # newline是数据之间不加空行
writer = csv.DictWriter(f, fieldnames=header)
# 或者writer = csv.DictWriter(f, header)
writer.writeheader() # 写入列名
writer.writerows(datas)
网友评论