我尝试使用MongoDB中的MongoDB获取的数据将一些数据写入CSV格式。目前,标题当前已设置,问题是实际数据未插入CSV文件。这是代码片段:
from pymongo import MongoClient
import csv
import os
conn = pymongo.MongoClient()
db = conn.clixster_dev
cursor = db.channels.find({},{'_id':0 , 'company-reg-no':0, 'isdel':0 , 'last_off':0 , 'last_on':0 , 'online':0 , 'password':0 , 'psotcode':0 , 'state':0 , 'subagent':0})
outfile = open( "asdxk.csv", "w" )
# get a csv writer
writer = csv.writer( outfile )
# write header
writer.writerow(['postcode', 'upline', 'cit_state', 'contact_person', 'contact_no','nominal_level', 'credit', 'level', 'account_holder', 'merchantid', 'email', 'bank', 'reg_date' ,'address','acc_no','company_name'])
# write data
[ writer.writerow(x) for x in cursor ]
# close file
outfile.close()
感谢任何考虑,
答案 0 :(得分:1)
您需要使用csv.DictWriter
代替 csv.writer
,因为您的查询结果是字典。
您还需要在查询中指定投影字段。
将您的查询更改为此。
cursor = db.channels.find({},{'_id':0, 'postcode': 1, 'upline': 1, 'cit_state': 1, 'contact_person': 1, 'contact_no': 1,'nominal_level': 1, 'credit': 1, 'level': 1, 'account_holder': 1, 'merchantid': 1, 'email': 1, 'bank': 1, 'reg_date': 1 ,'address': 1,'acc_no': 1,'company_name': 1})
并使用with
语句
with open('asdxk.csv', 'w') as outfile:
fields = ['postcode', 'upline', 'cit_state', 'contact_person', 'contact_no','nominal_level', 'credit', 'level', 'account_holder', 'merchantid', 'email', 'bank', 'reg_date' ,'address','acc_no','company_name']
writer = csv.DictWriter(outfile, fieldnames=fields)
writer.writeheader()
for x in cursor:
writer.writerow(x)