In a way, Python has this functionality built into the tempfile
module. Unfortunately, you have to tap into a private global variable, tempfile._name_sequence
. This means that officially, tempfile
makes no guarantee that in future versions _name_sequence
even exists -- it is an implementation detail.
But if you are okay with using it anyway, this shows how you can create uniquely named files of the form file#.pdf
in a specified directory such as /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'))
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…