Python DictReader和DictWriter读写csv文件
写入操作:
import csv
with open("name.csv",'w',newline='')as c:
file_name = ['first_name','last_name']
writer = csv.DictWriter(c,fieldnames=file_name)
# 写入列标题,即DictWriter构造方法的fieldnames参数
writer.writeheader()
# 写入值
writer.writerow({"first_name":"55","last_name":"666"})
writer.writerow({"first_name": "77", "last_name": "88"})
读取操作:
import csv
with open("name.csv")as f:
reader = csv.DictReader(f)
for row in reader:
print(row['first_name'],row['last_name'])