0
我有一個叫test.csv
CSV,看起來像:to_csv追加模式不追加到下一個新行
accuracy threshold trainingLabels
abc 0.506 15000
eew 18.12 15000
然後一個數據幀稱爲summaryDF
,看起來像:
accuracy threshold trainingLabels
def 0.116 342
dja 0.121 1271
我做:
try:
if os.stat('test.csv').st_size > 0:
summaryDF.to_csv(path_or_buf=f, encoding='utf-8', mode='a', header=False)
f.close()
else:
print "empty file"
with open('test.csv', 'w+') as f:
summaryDF.to_csv(path_or_buf=f, encoding='utf-8')
f.close()
except OSError:
print "No file"
with open('test.csv', 'w+') as f:
summaryDF.to_csv(path_or_buf=f, encoding='utf-8')
f.close()
因爲我希望我的文件是:
accuracy threshold trainingLabels
abc 0.506 15000
eew 18.12 15000
def 0.116 342
dja 0.121 1271
相反,它是:
accuracy threshold trainingLabels
abc 0.506 15000
eew 18.12 15000def 0.116 342
dja 0.121 1271
我怎樣才能解決這個問題?我猜測使用CSV編寫器而不是to_csv
,但顯然追加模式不會跳過現有文件的最後一行。