5

我在掌握 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_dictionary 是:

{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 的键名,并输出值。

相反,我得到:

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 库来执行此操作。谁能解释问题是什么?

4

1 回答 1

14

writerow不想writerows

前者采用单个参数,即要写入的行。后者采用可迭代的行。您正在writerows使用字典进行调用,该字典尝试遍历字典并写入每个条目。由于迭代 dicts 给出了它们的键,这与调用writerow(n6s2f0e1)which (显然)失败并出现您看到的错误相同。

于 2012-11-13T19:56:47.113 回答