在python 2.7中获取错误Nonetype

时间:2016-11-02 21:14:38

标签: python mongodb

我收到错误:

Traceback (most recent call last):
  File "<stdin>", line 9, in <module>
AttributeError: 'NoneType' object has no attribute 'get'

以下脚本有问题吗?我在脚本中使用了get(),因为Mongodb集合中缺少一些电话字段名称。

样本数据:

{
    "_id": ObjectID("57e99f88b948da6c3be04366"),
    "email": "jstahl2020@gmail.com",
    "phone": [
        {
            "type": "Mobile",
            "number": "250-851-1041"
        }
    ]}

python脚本:

import codecs
import csv
cursor = db.users.find ({}, {'_id':1, 'email': 1, 'phone.type':1, 'phone.number':1})
with codecs.open('applicatonmethod3.csv', 'w', encoding='utf-8') as outfile:        
        fields = ['_id', 'email', 'phone.type', 'phone.number'] 
        write = csv.DictWriter(outfile, fieldnames=fields)
        write.writeheader()    
        for x in cursor:
            x_id = x.get('_id')
            x_email = x['email']            
            y = x.get('phone')            
            z = {'_id': x_id,
                'email': x_email,
                'phone.type': y.get('type'),
                'phone.number': y.get('number')}                               
            write.writerow(z)
请某人帮助我。

2 个答案:

答案 0 :(得分:1)

您是否连接到正确的数据库,包含用户集合而不仅仅是默认数据库?

答案 1 :(得分:0)

我解决了这个问题。我和你分享。这是解决方案。谢谢你的帮助。

import sys
reload(sys)
sys.setdefaultencoding('utf-8')
import codecs
import csv
cursor = db.users.find ({}, {'_id':1, 'phone.type':1, 'phone.number':1, 'phone.extension':1})
with codecs.open('phone.csv', 'w', encoding='utf-8') as outfile:        
        fields =['_id', 'phone.type', 'phone.number', 'phone.extension'] 
        write = csv.DictWriter(outfile, fieldnames=fields)
        write.writeheader()    
        for x in cursor:
            x_id = x['_id']                                        
            for y in x.get('phone', {}):                                                                        
                z = {'_id': x_id,                                    
                    'phone.type': y.get('type'),
                    'phone.number': y.get('number'),
                    'phone.extension': y.get('extension')}
                print z                                                                                              
                write.writerow(z) 

cursor.close()