python csv与字典操作
# encoding: utf-8 import csv d1 = {'banana':3,'apple':4,'pear':1,'orange':2} d2 = {'banana':3,'orange':2} d3 = {} d4 = {'apple':4,'banana':3,'pear':1,'orange':2} headers = ['banana', 'apple','pear','orange'] datas = [d1,d2,d3,d4] #newline=''避免出现空行 with open('result.csv', 'w', newline='') as f: # 标头在这里传入,作为第一行数据 writer = csv.DictWriter(f, headers) writer.writeheader() for row in datas: writer.writerow(row) # 还可以写入多行 #writer.writerows(datas) with open('result.csv') as f: reader = csv.DictReader(f) print(type(reader)) print(reader) for row in reader: print(row) print(row['banana'])
<class 'csv.DictReader'> <csv.DictReader object at 0x00000000026009E8> OrderedDict([('banana', '3'), ('apple', '4'), ('pear', '1'), ('orange', '2')]) 3 OrderedDict([('banana', '3'), ('apple', ''), ('pear', ''), ('orange', '2')]) 3 OrderedDict([('banana', ''), ('apple', ''), ('pear', ''), ('orange', '')]) OrderedDict([('banana', '3'), ('apple', '4'), ('pear', '1'), ('orange', '2')]) 3 Process finished with exit code 0