As of Python 3.6 [f-strings format appeared]
A great solution is to use a function that takes 2 arguments and returns the first non-existed filename available. On the first iteration, the function tries to check if filename without any number exists. If this filename is already taken, the function tries to apply a number 0 right before the file extension. If this filename is already taken too, the function adds +1 to this number until non-existed filename will be found.
import os
def unique_filename(output_filename, file_extension):
n = ''
while os.path.exists(f'{output_filename}{n}{file_extension}'):
if isinstance(n, str):
n = -1
n += 1
return f'{output_filename}{n}{file_extension}'
For older Python versions you can use [%-strings format]
import os
def unique_filename(output_filename, file_extension):
n = ''
while os.path.exists('%s%s%s' % (output_filename, n, file_extension)):
if isinstance(n, str):
n = -1
n += 1
return '%s%s%s' % (output_filename, n, file_extension)
Another option is a function that takes file_path as an input argument.
file_path will be split into file path with filename and file extension (f.e. ".jpg")
import os
def unique_filename_path(file_path):
output_filename, file_extension = os.path.splitext(file_path)
n = ''
while os.path.exists(f'{output_filename}{n}{file_extension}'):
if isinstance(n, str):
n = -1
n += 1
return f'{output_filename}{n}{file_extension}'
filename_fix_existing(filename)- Grijesh Chauhan