Panda's Write CSV - Append vs. Write

232    Asked by Aalapprabhakaran in Python , Asked on Apr 24, 2021

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?

Answered by Asistha pandey

 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)

Your Answer

Interviews

Parent Categories