原文链接:http://www.juzicode.com/python-error-csv-valueerror-dict-contains-fields-not-in-fieldnames
错误提示:
csv模块写入记录提示ValueError: dict contains fields not in fieldnames: ‘age’
#juzicode.com/vx:桔子code
import csv
with open('test.csv','w',encoding='utf8',newline='') as f:
headers = ['sn','name']
writer = csv.DictWriter(f,headers)
writer.writeheader()
record={'sn':'1','name':'juzicode','age':'25'}
writer.writerow(record)
==========运行结果:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-1-b5e7edcc4478> in <module>
6 writer.writeheader()
7 record={'sn':'1','name':'juzicode','age':'25'}
----> 8 writer.writerow(record)
d:\python\python38\lib\csv.py in writerow(self, rowdict)
152
153 def writerow(self, rowdict):
--> 154 return self.writer.writerow(self._dict_to_list(rowdict))
155
156 def writerows(self, rowdicts):
d:\python\python38\lib\csv.py in _dict_to_list(self, rowdict)
147 wrong_fields = rowdict.keys() - self.fieldnames
148 if wrong_fields:
--> 149 raise ValueError("dict contains fields not in fieldnames: "
150 + ", ".join([repr(x) for x in wrong_fields]))
151 return (rowdict.get(key, self.restval) for key in self.fieldnames)
ValueError: dict contains fields not in fieldnames: 'age'
错误原因:
1、第8行写入的内容包含了3列,但是第4行定义的head只有2列,写入的列数多于head包含的列数。
解决方法:
1、需要修改head列数,适配要写入的内容的列数,这里需要将第 4行的内容增加一个元素:
#juzicode.com/vx:桔子code
import csv
with open('test.csv','w',encoding='utf8',newline='') as f:
headers = ['sn','name','age']#添加第3个head元素
writer = csv.DictWriter(f,headers)
writer.writeheader()
record={'sn':'1','name':'juzicode','age':'25'}
writer.writerow(record)
运行结果:
扩展内容:
如果本文还没有完全解决你的疑惑,你也可以在微信公众号“桔子code”后台给我留言,欢迎一起探讨交流。