Python Panda 的 Write CSV - Append vs. Write
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30991541/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Panda's Write CSV - Append vs. Write
提问by GPB
I would like to use pd.write_csv to write "filename" (with headers) if "filename" doesn't exist, otherwise to append to "filename" if it exists. If I simply use command:
如果“文件名”不存在,我想使用 pd.write_csv 写入“文件名”(带标题),否则附加到“文件名”(如果存在)。如果我只是使用命令:
df.to_csv('filename.csv',mode = 'a',header ='column_names')
The write or append succeeds, but it seems like the header is written every time an append takes place.
写入或追加成功,但似乎每次追加发生时都会写入标头。
How can I only add the header if the file doesn't exist, and append without header if the file does exist?
如果文件不存在,如何仅添加标题,如果文件存在,如何不添加标题?
采纳答案by Padraic Cunningham
Not sure there is a way in pandas but checking if the file exists would be a simple approach:
不确定大熊猫有没有办法,但检查文件是否存在将是一种简单的方法:
import os
# if file does not exist write header
if not os.path.isfile('filename.csv'):
df.to_csv('filename.csv', header='column_names')
else: # else it exists so append without writing the header
df.to_csv('filename.csv', mode='a', header=False)
回答by user3657041
with open(filename, 'a') as f:
df.to_csv(f, mode='a', header=f.tell()==0)
it will add header when writes to the file first time
第一次写入文件时它会添加标题
回答by VK Singh
In Pandas dataframe "to_csv" function, use header=False if csv file exists & append to existing file.
在 Pandas 数据框“to_csv”函数中,如果 csv 文件存在并附加到现有文件,则使用 header=False。
import os
hdr = False if os.path.isfile('filename.csv') else True
df.to_csv('filename.csv', mode='a', header=hdr)