Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (50.2k points)

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 append without a header if the file does exist?

1 Answer

0 votes
by (107k points)

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)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...