I want to save pandas dataframe to csv in overwrite mode. I want that whenever the program will run again with any changes then it should save the dataframe to csv and overwrite the already saved csv file at the location.
Asked
Active
Viewed 1.8k times
4 Answers
2
Python knows different file modes, among those w
stands for
Opens a file for writing only. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.
Because w
is the default for the mode in to_csv()
df.to_csv('file_name')
or be explicit (if needed):
df.to_csv('file_name', mode='w')

Michael Dorner
- 17,587
- 13
- 87
- 117
0
There are many ways you can do that .
This replaces file everytime you run the script.
dataframe.to_csv(r"C:\....\notebooks\file.csv")
This method first opens the files ,gives you options of reading(r) , appending(ab) or writing .
import csv
with open ('file.csv','w') as f:
wtr = csv.writer(f)

Shikha
- 229
- 3
- 5