Mansi Arora
Mansi Arora

Reputation: 97

How can i save a pandas dataframe to csv in overwrite mode?

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

Answers (4)

Michael Dorner
Michael Dorner

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

Shikha
Shikha

Reputation: 237

There are many ways you can do that .

  1. This replaces file everytime you run the script.

     dataframe.to_csv(r"C:\....\notebooks\file.csv")
    
  2. 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

Kokul Jose
Kokul Jose

Reputation: 1732

I think you can do:

df.to_csv('file_name.csv',mode='w+' )

Form more info goto documentation

Upvotes: 8

Edoardo Pericoli
Edoardo Pericoli

Reputation: 308

This should overwrite the file by default:

df.to_csv("filename")

Upvotes: 0

Related Questions