0

I need to be able to rename a file, continually increasing the number at the end of the file, without deleting a previous version of it. The original thought process was

file_path1 = "path/to/file/OLDqueues.sqlite"

try:
    os.remove(file_path1)
except OSError as e:
    print("Error: %s : %s" % (file_path1, e.strerror))

try:
   os.rename(r'path\to\file\queues.sqlite', r'path\to\file\OLDqueues.sqlite')
except OSError as e:
    print("Error: %s : %s" % (file_path1, e.strerror))

However, I've been told that we cannot delete the OLDqueues file in this process. What would be the best way to rename the file to OLDqueues, but if OLDqueues already exists- it will auto-rename to OLDqueues(1), then OLDqueues(2), etc?

For reference, I am using Python 3.7, and this will be applied to two files in different locations, but must not affect any other files in the directory.

TLBones
  • 3
  • 3
  • The best way would be to check if OLDqueues already exists and if so, check if OLDqueues(1) exists, etc., until you find a filename that doesn't exist yet, and then to use that filename. – mkrieger1 Jun 02 '21 at 17:34
  • If this is all in the same thread, a local variable could be used as a cache, otherwise a loop using a glob of 'OLDqueues' and increment for each existing file with the name until done and then rename with the increment +=1 – pypalms Jun 02 '21 at 17:36
  • Does this answer your question? [How do I create a file in python without overwriting an existing file](https://stackoverflow.com/questions/1348026/how-do-i-create-a-file-in-python-without-overwriting-an-existing-file) – mkrieger1 Jun 02 '21 at 17:36

1 Answers1

1

If you don't want to remove the old file, just save incremental versions, I am not sure why you are trying to delete that file?

This is the way I have implemented this in the past:

if os.path.exists(file_path1):
    file_path2 = ## insert file name increment logic here
    # copy file as described in the link below using shutil

https://stackabuse.com/how-to-copy-a-file-in-python

RustyB
  • 147
  • 1
  • 11