Python csvwriter最多只能写入132行

时间:2015-05-24 03:28:21

标签: python csv export-to-csv

我正在尝试将存储在python字典中的数据写入csv文件。由于某种原因,最后15行左右不会在csv文件中结束。 python字典的格式如下:

{name:{key1:value1,key2:value2},
name:{key1:value1,key2:value2},
name:{key1:value1,key2:value2},
name:{key1:value1,key2:value2,key3:value3},
}

我之前就让它工作了所以我知道它可能,我只是不记得我做了什么。

这是我的代码:

featuresq =['name', 
'to_messages', 
'deferral_payments', 
'expenses', 
'poi', 
'deferred_income', 
'email_address', 
'long_term_incentive', 
'restricted_stock_deferred', 
'shared_receipt_with_poi', 
'loan_advances', 
'from_messages', 
'other', 
'director_fees', 
'bonus', 
'total_stock_value', 
'from_poi_to_this_person', 
'from_this_person_to_poi', 
'restricted_stock', 
'salary', 
'total_payments', 
'exercised_stock_options']

for name,line in data_dict.items():
    line["name"]=name
    row=[]
    for feature in featuresq:
    #   if feature in line.keys():\
        try:
            row.append(line[feature])
     #  else:
        except:
            row.append(float('NaN'))
    f.writerow(row)

1 个答案:

答案 0 :(得分:0)

尝试使用

    #This will close your file correctly if any untoward termination occurs. 
    with open('csv-file.csv','wb') as myfile: 
         # for testing purposes - you may flush each row to the file
         myfile.flush() 

其次,我建议您使用row.append(line.get(feature, float('nan')))而不是try和except。字典有一个内置的get函数,可以完全按照try-and-except执行的操作,并为您提供更多的代码 -

for name,line in data_dict.items():
    line["name"]=name
    row=[]
    for feature in featuresq:
        row.append(line.get(feature, float('nan')))
    f.writerow(row)
    FILE.flush()