Panda's Write CSV - Append vs. Write
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 the command:
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 pandas to_csv append without a header if the file does exist?
Checking the existence of file would be a simple approach, refer the following code:
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 mentioning the header
df.to_csv('filename.csv', mode='a', header=False)