This is a detail where it's a bit platform dependent. If you were using Windows, you would have gotten a FileExistsError
exception thrown, but not on Unix.
This is what the documentation says:
Rename the file or directory src to dst. If dst exists, the operation will fail with an OSError subclass in a number of cases:
On Windows, if dst exists a FileExistsError is always raised.
On Unix, if src is a file and dst is a directory or vice-versa, an IsADirectoryError or a NotADirectoryError will be raised respectively. If both are directories and dst is empty, dst will be silently replaced. If dst is a non-empty directory, an OSError is raised. If both are files, dst it will be replaced silently if the user has permission. The operation may fail on some Unix flavors if src and dst are on different filesystems. If successful, the renaming will be an atomic operation (this is a POSIX requirement).
So you need to perform a manual check if the file exists, and if it does, handle it in some way.
One thing that probably won't affect your program is that a check on this (from alaniwi's answer) form:
while os.path.exists(new_filename):
value += 1
new_filename = f'wallpaper{value}.jpg'
os.rename(file, new_filename)
is not entirely safe. In between the event that you have established that a filename is free and the event when you start writing, another process might create a file with that name. If that is a concern, have a look at this question
A combination of alaniwi's approach and this could look like this:
while True:
value += 1
new_filename = f'wallpaper{value}.jpg'
try:
os.open(new_filename, os.O_CREAT | os.O_EXCL)
break
except FileExistsError:
pass
The basic principle is that you can never know in advance if an operation will succeed or not. So what you need to do is to an attempt to perform an operation and see if it succeeded.