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

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'))

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

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How can I read system information in Python on Windows?(如何在 Windows 上读取 Python 中的系统信息?)
How to get the newest directory in Python(如何在 Python 中获取最新目录)
Python - Get Path of Selected File in Current Windows Explorer(Python - 在当前 Windows 资源管理器中获取所选文件的路径)
Print out the whole directory tree(打印出整个目录树)
Python os.stat and unicode file names(Python os.stat 和 unicode 文件名)
A system independent way using python to get the root directory/drive on which python is installed(使用 python 获取安装 python 的根目录/驱动器的系统独立方式)