1

I was wondering how I can overwrite an existing .csv file in the same file directory called test.csv

My following program opens the test.csv file it then appends some string names to it and is then called "main" dataframe. I was wondering how I can save "main" to the same directory as test.csv. Therefore replacing the old test.csv with the new one.

import pandas as pd

main=pd.read_csv('C:/Users/Jonas/Desktop/testfile/test.csv', header=None)

target_col = ['dog'] * main.shape[0]
target_col[0] = 'target'
main.insert(loc = 0, column = -1, value = target_col)
main.rename(columns = lambda x:x+1,inplace=True) #Reorients -1 to the origin
#How to rewrite test.csv?

Image showing the old test.csv file and the new "Final" dataframe: enter image description here

Thanks. Below shows the saved data error: enter image description here

2 Answers2

1

Use to_csv

main.to_csv('C:/Users/Jonas/Desktop/testfile/test.csv', header=None)
Tobi208
  • 1,306
  • 10
  • 17
  • When I view my new data from excel It has another column going down 0, 1, 2, 3 rows. I've attached another image on the post showing this. I'm wondering how I can make python save the .csv file without this unnecessary column? Cheers. – Python_warrior Feb 02 '22 at 12:48
  • use "index=False" as another option after "header=None", see my answer and mark both answers as correct please. – Mattis Seehaus Feb 02 '22 at 12:51
1
 main.to_csv('C:/Users/Jonas/Desktop/testfile/test.csv', header=None, index=False)
Mattis Seehaus
  • 114
  • 1
  • 11