Search code examples
pythoncsvdirectoryoverwrite

Overwrite .csv file in directory


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


Solution

  •  main.to_csv('C:/Users/Jonas/Desktop/testfile/test.csv', header=None, index=False)