Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Skip header after the first time CSV file is written into (Python)

The following script for writing to a CSV file is going to run on a server which will automate the run.

    d = {'col1': a, col2': b, col3': c,}
    df = pandas.DataFrame(d, index = [0])
    with open('foo.csv', 'a') as f:
            df.to_csv(f, index = False)    

The problem is, everytime I run it, the header gets copied to the CSV file. How can I modify this code to have the header copied to the CSV file only the first time its run, and never after that?

Any help will be appreciated :)

like image 380
ThatRiddimGuy Avatar asked Dec 24 '22 03:12

ThatRiddimGuy


1 Answers

try this:

filename = '/path/to/file.csv'
df.to_csv(filename, index=False, mode='a', header=(not os.path.exists(filename)))
like image 153
MaxU - stop WAR against UA Avatar answered Dec 26 '22 19:12

MaxU - stop WAR against UA