Rename a file as an alternative name concisely when FileExistsError in python

Viewed 411

Let's say:

  • I'd like to rename a file original.txt as name.txt.
  • If name.txt exists, rename as name(0).txt.
  • If name(0).txt exists, rename as name(1).txt, and so on.
  • I don't want to delete nor overwrite the same name files.

I came up the code that achieves this, but utterly verbose.

import os

try:
    os.rename("original.txt", "name.txt")
except FileExistsError:
    i = 0
    while True:
        try:
            os.rename("original.txt", f"name({i}).txt")
            break
        except:
            if i >= 9:
                raise Exception("Too many same name files")
            i += 1
except:
    print("Unexpected error")

Is there a more suitable function or concise way to do this?

By the way, this post is related, however, the all answers assume the same name files can be deleted, which is not true in my case.

Edit: To be clear, I think it's appopriate to add the following requirements.

  • It should be checked whether the file is successfully created after operation.
  • Any errors should be catched by except.
1 Answers

You Can try using a for loop like this:

import os

original_filename = 'original.txt'

for number in range(0, 10000, 1):
    try:
        #Cheking whether the file exists
        #If the file exists, then it will raise FileExistsError
        #Else create a file
        try_to_create_a_file = open(f'name{number}.txt', 'x')

        #If the file is created by the above code, then delete the file
        os.remove('name{number}.txt')

        #Then rename the file
        os.rename(original_filename, f'name{number}.txt')

       #Then break the for loop
       break
    except FileExistsError:
       #Continue the for loop if the file exists
       continue
Related