【发布时间】:2016-12-25 08:06:18
【问题描述】:
我有一个名为 test.csv 的 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,但显然附加模式不会跳过现有文件的最后一行。
【问题讨论】:
标签: python csv append export-to-csv