Let's say:
- I'd like to rename a file
original.txt
asname.txt
. - If
name.txt
exists, rename asname(0).txt
. - If
name(0).txt
exists, rename asname(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
.