3 回答
TA贡献1784条经验 获得超2个赞
由于数据是字典,因此csv.DictWriter()可能是最直接的方法。只需确保标头值列表按原始顺序排列即可,在这种情况下,这sorted()可能是最简单的:
with open('Ouput1.csv', 'wt') as csvfile:
fieldnames = sorted(row.keys()) # needs to be the first line in correct order
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
writer.writerow(row) # writes corresponding value for key in header
TA贡献2011条经验 获得超2个赞
row是 类型dict。从文档:
import csv
with open('names.csv', 'w') as csvfile:
fieldnames = ['first_name', 'last_name']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
writer.writerow({'first_name': 'Baked', 'last_name': 'Beans'})
writer.writerow({'first_name': 'Lovely', 'last_name': 'Spam'})
writer.writerow({'first_name': 'Wonderful', 'last_name': 'Spam'})
添加回答
举报