赞
踩
我在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
我的印象是,作家通过提供的字典,使用提供的dictwriter字段名称调用所提供的字典的键名,并输出值.
相反,我得到:
Traceback (most recent call last):
File "", line 3, in
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库来实现这一点.任何人都可以解释这个问题是什么?
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。