从某种意义上说,Python在
tempfile模块中内置了此功能。不幸的是,您必须利用私有全局变量
tempfile._name_sequence。正式地,这意味着
tempfile不能保证
_name_sequence甚至在将来的版本中都存在-
这是实现细节。但是,如果您可以使用它,可以说明如何
file#.pdf在指定的目录中创建具有唯一名称的表单文件,例如
/tmp:
import tempfileimport itertools as ITimport osdef 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 filenameprint(uniquify('/tmp/file.pdf'))
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)