CSV,Python:正确使用DictWriter(ValueError:dict包含字段名以外的字段)

2024-04-26 22:29:07 发布

您现在位置:Python中文网/ 问答频道 /正文

在csv模块(Python 2.7)中,我很难掌握DictWriter。我有这个(哦,我正在使用unicodecsv库,因为我读到了一些问题):

f = object_instance.return_a_dictionary.keys()
with open('eggs.csv', 'wb') as csvfile:
    spamwriter = unicodecsv.DictWriter(csvfile, fieldnames=f)
    spamwriter.writerows(object_instance.return_a_dictionary)

所以我通过了我的对象实例。f是:

[u'n6s2f0e1', u'n1s0f0e0', u'n2s0f0e1', u'n3s1f0e0', u'n5s2f0e0', u'n4s1f0e1']

object_instance.return_a_字典是:

{u'n6s2f0e1': u'stuff', u'n1s0f0e0': u'stuff', u'n2s0f0e1': u'stuff', u'n3s1f0e0': u'stuff', u'n5s2f0e0': u'stuff', u'n4s1f0e1': u'stuff'}

所以我真的想要第一排:

stuff stuff stuff stuff stuff

我的印象是writerow遍历提供的字典,用提供的dictwriter字段名调用提供的dict的keyname,并输出值。

相反,我得到:

Traceback (most recent call last):
File "<stdin>", line 3, in <module>
File "/usr/lib/python2.7/csv.py", line 153, in writerows
rows.append(self._dict_to_list(rowdict))
>>> File "/usr/lib/python2.7/csv.py", line 144, in _dict_to_list
", ".join(wrong_fields))
ValueError: dict contains fields not in fieldnames: n, 6, s, 2, f, 0, e, 1

我只是现在不明白。它使用常规的Python csv库和我找到的unicode csv库来实现这一点。有人能解释一下问题是什么吗?


Tags: csvcsvfileinstanceindictionaryreturnobjectline
1条回答
网友
1楼 · 发布于 2024-04-26 22:29:07

你想要的是writerow而不是writerows

前者只需要一个参数,即要写入的行。后者需要相当多的行。您正在使用字典调用writerows,该字典尝试遍历字典并编写每个条目。由于对dict的迭代给出了它们的键,这与调用writerow(n6s2f0e1)是一样的,调用writerow(n6s2f0e1)显然会失败,并出现错误。

相关问题 更多 >