更新时间:2023-01-09 12:28:43
此处的真正问题是,尽管您在问题中声明了什么,但其他所有字段名都不包含在此内容中电子表格.
The real problem here is that, despite what you claim in your question, all of the others' fieldnames are not included in this spreadsheet.
您可以通过查看所提出的那一行上方的内容来判断. DictWriter._dict_to_list
看起来像这样:
You can tell by looking at the line above the one that raised. DictWriter._dict_to_list
looks like this:
def _dict_to_list(self, rowdict):
if self.extrasaction == "raise":
wrong_fields = [k for k in rowdict if k not in self.fieldnames]
if wrong_fields:
raise ValueError("dict contains fields not in fieldnames: " +
", ".join(wrong_fields))
return [rowdict.get(key, self.restval) for key in self.fieldnames]
因此,它找到了不在您的DictWriter
中的字段.
So, it found a field that isn't in your DictWriter
.
但是为什么在尝试创建错误时却引发了这个奇怪的错误呢?因为缺少的字段被命名为None
. DictWriter
代码不是用于处理此问题的.所以,这就是问题2.
But why is it raising that weird error while trying to create the error? Because the missing field is named None
. The DictWriter
code isn't built to handle that. So, that's problem #2.
为什么将该字段命名为None
?因为DictReader
每当它找到不适合您提供的fieldnames
的列时,这就是产生的结果.您可以通过print row
看到这一点:dict
的元素之一将类似于None: 'foo'
.因此,这就是问题3.
And why is the field named None
? Because that's what a DictReader
produces whenever it finds a column that doesn't fit into the fieldnames
that you gave it. You can see this by print row
: One of the elements of the dict
will be something like None: 'foo'
. So, that's problem #3.
那么您如何解决呢?
好吧,显而易见的事情是使您的主张正确:使目标中的字段成为源中字段的严格超集.
Well, the obvious thing to do is make your claim true: Make the fields in your target a strict superset of the fields in your source.
或者,您可以告诉您DictReader
跳过多余的字段,或者告诉您DictWriter
忽略它们而不是加注.例如,只需将extrasaction='ignore'
添加到您的DictWriter
构造函数中,问题就会消失.
Alternatively, you can tell your DictReader
to skip extra fields, or your DictWriter
to ignore them instead of raising. For example, just add extrasaction='ignore'
to your DictWriter
constructor, and the problem will go away.
但实际上,您不应该那样做. raise
在这里为您找到了一个合法的错误;只是没有这样做,却显示了非常有用的错误消息.
But really, you shouldn't be doing that. raise
caught a legitimate bug for you here; it just didn't do so with a very useful error message.