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
,但显然追加模式不会跳过现有文件的最后一行。