Panda's Write CSV - Append vs. Write

后端 未结 3 657
眼角桃花
眼角桃花 2020-11-30 00:10

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 co

相关标签:
3条回答
  • 2020-11-30 01:12
    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

    0 讨论(0)
  • 2020-11-30 01:13

    In Pandas dataframe "to_csv" function, use header=False if csv file exists & append to existing file.

        import os
    
        hdr = False  if os.path.isfile('filename.csv') else True
        df.to_csv('filename.csv', mode='a', header=hdr)
    
    0 讨论(0)
  • 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)
    
    0 讨论(0)
提交回复
热议问题