In a way, Python has this functionality built into the tempfile module. Unfortunately, you need to connect to the private global variable tempfile._name_sequence . This means that officially tempfile does not guarantee that in future versions of _name_sequence even exists - this is an implementation detail. But if you use it anyway, it will show how you can create uniquely named files of the form file#.pdf in the specified directory, for example /tmp :
import tempfile import itertools as IT import os def uniquify(path, sep = ''): def name_sequence(): count = IT.count() yield '' while True: yield '{s}{n:d}'.format(s = sep, n = next(count)) orig = tempfile._name_sequence with tempfile._once_lock: tempfile._name_sequence = name_sequence() path = os.path.normpath(path) dirname, basename = os.path.split(path) filename, ext = os.path.splitext(basename) fd, filename = tempfile.mkstemp(dir = dirname, prefix = filename, suffix = ext) tempfile._name_sequence = orig return filename print(uniquify('/tmp/file.pdf'))
source share