blu*_*ank 5 python csv unicode dictionary
我在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)
Run Code Online (Sandbox Code Playgroud)
所以我传入了我的对象实例.f是:
[u'n6s2f0e1', u'n1s0f0e0', u'n2s0f0e1', u'n3s1f0e0', u'n5s2f0e0', u'n4s1f0e1']
Run Code Online (Sandbox Code Playgroud)
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'}
Run Code Online (Sandbox Code Playgroud)
所以我真的想要第一排:
stuff stuff stuff stuff stuff
Run Code Online (Sandbox Code Playgroud)
我的印象是,作家通过提供的字典,使用提供的dictwriter字段名称调用所提供的字典的键名,并输出值.
相反,我得到:
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
Run Code Online (Sandbox Code Playgroud)
我现在还不明白这一点.它使用常规的Python csv库和我发现的unicode csv库来实现这一点.任何人都可以解释这个问题是什么?
Kat*_*iel 14
你writerow不想要writerows.
前者采用单个参数,即要写入的行.后者采用可迭代的行.您正在writerows使用字典进行调用,该字典尝试迭代字典并写入每个条目.由于遍历dicts给出了它们的密钥,这与调用writerow(n6s2f0e1)哪个(显然)因你看到的错误而失败是一样的.
| 归档时间: |
|
| 查看次数: |
12025 次 |
| 最近记录: |