我试图使用Python将数据从Mongodb导出到csv。我收到错误: “类型错误:只能加入一个可迭代”使用python将数据导出到csv时出现错误
MongoDB的数据样本:
{ "_id" : ObjectId("51dc52fec0d988a9547b5201"),
"hiringManagerIds" : [
"529f5ad1030dedd0a88ed7be",
"529f5ad1030dedd0a88ed7bf"
]
}
Python脚本:
import codecs
import csv
cursor = db.jobs.find({}, {'_id': 1, 'hiringManagerIds': 1})
with codecs.open('jobs_array.csv', 'w', encoding ='utf-8') as outfile:
fields = ['_id', 'hiringManagerIds']
write = csv.writer(outfile)
write.writerow(fields)
for x in cursor:
write.writerow((x["_id"], u','.join(x.get('hiringManagerIds'))))
错误信息:
Traceback (most recent call last):
File "<stdin>", line 6, in <module>
TypeError: can only join an iterable
我想要删除u字母,所以我在脚本中使用u.join。 hiringManagerIds文件在某些文档中丢失,所以我使用get。如果我不添加u''加入脚本,它可以工作,但它会在csv文件中带来u字母。我尝试了很多不同的方式,但没有奏效。感谢您的帮助。谢谢。
什么'打印x.get( 'hiringManagerIds')'吗? – inspectorG4dget
此代码不会运行:第一个块最后一行的缩进不正确? –
它给出了hiringmanagerids的值:[u'529f5ad1030dedd0a88ed7be',u'529f5ad1030dedd0a88ed7bf'] 谢谢 – user7070824