How to force a new line when appending to a csv using python pandas .to_csv

前端 未结 3 947
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-12 17:38

When appending to csv, my first line is starting on the existing last line rather than a new line.

I keep searching SO, but I am just finding the basic use of openi

相关标签:
3条回答
  • 2021-01-12 18:04

    I am assuming that you are going to appending one below other of two dataframe into single dataframe.

    use below mentioned command to make it as single command

    ans = pd.concat([df, df])

    then you can make output into .csv file

    0 讨论(0)
  • 2021-01-12 18:13

    I had a similar problem and after a god bit of searching, I didn't find any simple/elegant solution. The minimal fix that worked for me is:

    import pandas as pd
    
    with open('foo.csv') as f:
        f.write('\n')    
    mydf.to_csv('foo.csv', index = False, header = False, mode='a')
    
    0 讨论(0)
  • 2021-01-12 18:20

    If your dataframe gets huge and you want to avoid concatenation you could go with

    import csv
    with open('foo.csv','ab') as out:
       writer=csv.writer(out)
       writer.writerow(())
    

    in a function or just as a snippet in your code. If you're not on Windows maybe you could avoid adding 'b' in open and open the file with just 'a' (append)

    0 讨论(0)
提交回复
热议问题