简体   繁体   English

使用python将数据导出到csv时出错

[英]getting error when export data to csv by using python

I tried to export data to csv from Mongodb by using Python. 我尝试使用Python将数据从Mongodb导出到csv。 I am getting error: "TypeError: can only join an iterable" 我收到错误消息:“ TypeError:只能加入可迭代对象”

mongodb data sample: mongodb数据样本:

{ "_id" : ObjectId("51dc52fec0d988a9547b5201"),
  "hiringManagerIds" : [ 
        "529f5ad1030dedd0a88ed7be", 
        "529f5ad1030dedd0a88ed7bf"
    ]
  }

Python script: 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'))))

error messages: 错误讯息:

Traceback (most recent call last):
File "<stdin>", line 6, in <module>
TypeError: can only join an iterable

I want to remove u letters so I use u.join in the script. 我想删除u字母,所以我在脚本中使用u.join。 the hiringManagerIds filed is missing in some document, so I use get. 某些文档中缺少hiringManagerIds字段,因此我使用get。 If I don't add u''.join in the script, it works, but it brings u letters in the csv file. 如果我不在脚本中添加u''。join,它可以工作,但是会在csv文件中带来u字母。 I tried many different ways, but it did not work. 我尝试了许多不同的方法,但是没有用。 Appreciate for any helps. 感谢任何帮助。 thanks. 谢谢。

The error stems from one of the documents not having hiringManagerIds. 该错误源于没有hiringManagerIds的文档之一。 If this is undefined, at present your code returns None into the join method, which requires an iterable (None is not an iterable). 如果未定义,则当前您的代码将None返回到join方法,该方法需要可迭代(None不可迭代)。

You should check if the key is present in the dictionary first: 您应该先检查字典中是否存在密钥:

if 'hiringManagerIds' in x.keys():
    write.writerow((x["_id"], u','.join(x.get('hiringManagerIds'))))
else:
    write.writerow((x["_id"], '')))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM