mongodb dict to python中的csv,UnicodeEncodeError

时间:2015-04-24 03:06:07

标签: python csv

在使用pymongo处理一些数据的最后,我有一个列表email_list[]。我跑的时候:

for z in range (0,5):
    print email_list[z]

我明白了:

{u'_id': ObjectId('52ab110e763f4aec448b670a'), u'email': u'first.last@email.com'}
{u'_id': ObjectId('52cc62bc763f4aec418b46f8'), u'email': u'test.smith@gmail.com'}
{u'_id': ObjectId('52b4b2a0763f4a61198b4760'), u'email': u'jim.doe@hotmail.com'}
{u'_id': ObjectId('52bae9b3763f4a9c4b8b4575'), u'email': u'foo@bar.com'}
{u'_id': ObjectId('52c2e3e6763f4a572d8b45e3'), u'email': u'bill@gmail.com'}

我试图将列表写入csv。我有:

my_dict = email_list[0]

with open('new_file.csv','wb') as f:
    w = csv.DictWriter(f,my_dict.keys())
    w.writeheader()
    w.writerow(my_dict)
    for row in email_list:
        w.writerow(row)

我收到以下错误:

Traceback (most recent call last):
File "mongodb_script_1.py", line 74, in <module>
w.writerow(row)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/csv.py", line 148, in writerow
return self.writer.writerow(self._dict_to_list(rowdict))
UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 22: ordinal not in range(128)

但是,文件new_file.csv似乎有ID和电子邮件。

发生了什么?

1 个答案:

答案 0 :(得分:0)

试试这个:

import unicodecsv as csv
with open('new_file.csv','w') as f:
w = csv.DictWriter(f,my_dict[0].keys())
w.writeheader()
for row in t:
    del row['_id']
    w.writerow(row)

你不能在csv中插入'_id',因为它是mongodb的一个对象,在插入之前将其删除