How to add pandas data to an existing csv file? How to add pandas data to an existing csv file? python python

How to add pandas data to an existing csv file?


You can specify a python write mode in the pandas to_csv function. For append it is 'a'.

In your case:

df.to_csv('my_csv.csv', mode='a', header=False)

The default mode is 'w'.


You can append to a csv by opening the file in append mode:

with open('my_csv.csv', 'a') as f:    df.to_csv(f, header=False)

If this was your csv, foo.csv:

,A,B,C0,1,2,31,4,5,6

If you read that and then append, for example, df + 6:

In [1]: df = pd.read_csv('foo.csv', index_col=0)In [2]: dfOut[2]:   A  B  C0  1  2  31  4  5  6In [3]: df + 6Out[3]:    A   B   C0   7   8   91  10  11  12In [4]: with open('foo.csv', 'a') as f:             (df + 6).to_csv(f, header=False)

foo.csv becomes:

,A,B,C0,1,2,31,4,5,60,7,8,91,10,11,12


with open(filename, 'a') as f:    df.to_csv(f, header=f.tell()==0)
  • Create file unless exists, otherwise append
  • Add header if file is being created, otherwise skip it