Python csvwriter 最多只能写入 132 行

Python csvwriter only writes up to 132 rows

我正在尝试将存储在 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)

尝试使用

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