Does Python have any built-in functionality to add a number to a filename if it already exists?
My idea is that it would work the way certain OS's work - if a file is output to a directory where a file of that name already exists, it would append a number or increment it.
I.e: if "file.pdf" exists it will create "file2.pdf", and next time "file3.pdf".
To check if a file exists, you pass the file path to the exists() function from the os. path standard library. If the file exists, the exists() function returns True . Otherwise, it returns False .
To create a file if not exist in Python, use the open() function. The open() is a built-in Python function that opens the file and returns it as a file object. The open() takes the file path and the mode as input and returns the file object as output.
I ended up writing my own simple function for this. Primitive, but gets the job done:
def uniquify(path): filename, extension = os.path.splitext(path) counter = 1 while os.path.exists(path): path = filename + " (" + str(counter) + ")" + extension counter += 1 return path
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With