创建文件,但如果名称存在,则添加编号 [英] 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?
我的想法是,它将以某些OS的工作方式工作-如果将文件输出到已经存在该名称文件的目录中,它将添加数字或递增数字.
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
:
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屋!