-1

Is there a way of using to_csv("xxx.csv") in Python without overwriting an existing file?

In other words, if I ran to_csv("xxx.csv") twice in succession, I would like to have 2 output files in my folder, not one.

MRHarv
  • 491
  • 1
  • 10
  • 22

2 Answers2

0

In order to have two different files, you need to give them two different names. There is no way around this, and it makes sense and is usually enforced at the OS level.

You can try it yourself by trying to create two files with the same name via the terminal or a GUI.

saq7
  • 1,528
  • 1
  • 12
  • 25
  • I was hoping the second time I ran `to_csv("xxx.csv")` , the file gets named as xxx(1).csv instead of overwriting, but I guess it is just not possible. Thanks. – MRHarv Jan 09 '19 at 15:50
  • It is possible, you have to tell python to do that though. It does not do it inherently because that is generally not desired behavior. – d_kennetz Jan 09 '19 at 15:51
  • Where would I look, to be able to tell python to do this? – MRHarv Jan 09 '19 at 15:56
  • Change the file path like `/data/location_1/myfile.csv` and next time `/data/location_2/myfile.csv` then you have same file name! – Karn Kumar Jan 09 '19 at 15:59
  • There is no way to "tell" python other than giving it a new name string everytime it is called. You'd also need to keep track of the number of times it's been called to append the number to the end – saq7 Jan 09 '19 at 19:30
0

Answering my own question for the benefit of other users. I am running a monthly process and so the only way to not overwrite files is to use .format() within the file name.

e.g. .to_csv("xxx{}.csv".format(a), index=False), where a increases by 1 each month, so there is no overwriting involved.

MRHarv
  • 491
  • 1
  • 10
  • 22