Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create file but if name exists add number

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".

like image 783
Parham Avatar asked Dec 13 '12 03:12

Parham


People also ask

How do I make sure a file exists?

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 .

How do you create a file if not exist in Python?

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.


1 Answers

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 
like image 60
S. Tarık Çetin Avatar answered Sep 20 '22 14:09

S. Tarık Çetin