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'))
这篇关于创建文件,但如果名称存在添加编号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:创建文件,但如果名称存在添加编号


基础教程推荐
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- 包装空间模型 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- 求两个直方图的卷积 2022-01-01