使用下面的代码,我正在将CSV文件读入字典,并在'fieldname'
变量中设置了字段名称。每个字段名称在CSV文件中都有对应的值。
打印每个字段名称时,两个给我
" KeyError:'月'"和" KeyError:'年'"
所有其他人都能正常显示。不确定是什么导致了这一点。此外,当尝试将每个字段名称的内容写入新文件时,我收到错误wrong_fields = rowdict.keys() - self.fieldnames
AttributeError: 'str' object has no attribute 'keys'"
代码:
import csv
with open('mmns.csv','r') as csv_file:
csv_reader = csv.DictReader(csv_file)
with open('c1.csv', 'w') as new_file:
fieldnames = ['Day', 'Month', 'Year', 'c1', 'c2', 'c3', 'c4', 'c5', 'c6']
csv_writer = csv.DictWriter(new_file, fieldnames=fieldnames,delimiter=',')
for line in csv_reader:
print(line['c1'])
csv_writer.writerow(line['c1'])