1、使用csv.DictWriter()写入字典格式的数据
代码语言:javascript复制import csv
with open('test.csv', 'w', newline='') 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'})
运行之后结果:
2、使用csv.DictReader()读取字典格式的数据
代码语言:javascript复制with open('test.csv', 'r') as csvfile:
#fieldnames = ['first_name', 'last_name']
reader = csv.DictReader(csvfile)
for row in reader:
print(row['first_name'],row['last_name'])
运行之后结果: