创建文件,但如果名称存在添加编号

时间:2023-04-28
本文介绍了创建文件,但如果名称存在添加编号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

如果文件名已经存在,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'))

这篇关于创建文件,但如果名称存在添加编号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!

上一篇:Python 中 os.system() 的返回值是什么? 下一篇:何时使用 os.name、sys.platform 或 platform.system?

相关文章

最新文章