Home > Back-end >  appending a df to new row of csv file adds a empty row between added data
appending a df to new row of csv file adds a empty row between added data

Time:12-24

I want to append this single rowed df

rndList = ["albert", "magnus", "calc", 2, 5, "drop"]

rndListDf = pd.DataFrame([rndList])

to a new row of this csv file ,

first,second,third,fourth,fifth,sixth

to place each value under the corespondent column header

using this aproach

rndListDf.to_csv('./rnd_data.csv', mode='a', header=False)

leaves a empty row between header and data in the csv file
how can I append the row without the empty row ?

first,second,third,fourth,fifth,sixth


0,albert,magnus,calc,2,5,drop


CodePudding user response:

I think you have empty lines after your header rows but you can try:

data = pd.read_csv('./rnd_data.csv')
rndListDf.rename(columns=dict(zip(rndListDf.columns, data.columns))) \
         .to_csv('./rnd_data.csv', index=False)

Content of your file after this operation:

first,second,third,fourth,fifth,sixth
albert,magnus,calc,2,5,drop

CodePudding user response:

I tested. Code or pandas.to_csv doesn't append new line. It comes from your original csv file. If you are trying to figure out how to add heading to your dataframe:

rndList = ["albert", "magnus", "calc", 2, 5, "drop"]
rndListDf = pd.DataFrame([rndList])

rndListDf.columns = 'first,second,third,fourth,fifth,sixth'.split(',')
rndListDf.to_csv('./rnd_data.csv', index=False)
  • Related