2

I'm trying to write some data into CSV format using fetched data from MongoDB, with Mongopy. Currently, the headers are currently set, and the problem is that the actual data is not being inserted into the CSV file. here is the code snippet :

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()

Any consideration is appreciated,

Pouya Ataei
  • 1,959
  • 2
  • 19
  • 30
  • Why this is not writing into file. Add try catch block in file operations. Check if any exceptions occurred while writing data. Simply debug the code – ajay_t Feb 26 '15 at 07:42

1 Answers1

1

You need to use csv.DictWriter instead of csv.writer because your query results are dictionaries. You also need to specify your projection fields in your query. Change your query to this.

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})

and use the with statement

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)
styvane
  • 59,869
  • 19
  • 150
  • 156