Reputation: 97
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.
Upvotes: 7
Views: 26594
Reputation: 20155
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')
Upvotes: 2
Reputation: 237
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)
Upvotes: 0
Reputation: 1732
I think you can do:
df.to_csv('file_name.csv',mode='w+' )
Form more info goto documentation
Upvotes: 8
Reputation: 308
This should overwrite the file by default:
df.to_csv("filename")
Upvotes: 0