创建文件但如果名称存在则添加数字 [英] Create file but if name exists add number
问题描述
如果文件名已经存在,Python 是否具有向文件名添加数字的任何内置功能?
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.
即:如果file.pdf"存在,它将创建file2.pdf",下次创建file3.pdf".
I.e: if "file.pdf" exists it will create "file2.pdf", and next time "file3.pdf".
推荐答案
在某种程度上,Python 将此功能内置到 tempfile
模块中.不幸的是,您必须使用私有全局变量 tempfile._name_sequence
.这意味着官方 tempfile
不保证在未来版本中 _name_sequence
甚至存在——这是一个实现细节.但是,如果您无论如何都可以使用它,这将显示您如何在指定的目录(例如 /tmp
)中创建形式为 file#.pdf
的唯一命名的文件:
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'))
这篇关于创建文件但如果名称存在则添加数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!