python:创建文件,但如果名称存在则添加数字

Par*_*ham 15 python file-io operating-system

python是否有任何内置功能?我的想法是,如果将文件输出到已存在该名称的文件的目录,它将以某种操作系统的工作方式工作.即:如果"file.pdf"存在,它将创建"file2.pdf",并且下次"file3.pdf".

S. *_*tin 13

我最终为此编写了自己的简单函数。原始,但完成工作:

def uniquify(path):
    filename, extension = os.path.splitext(path)
    counter = 1

    while os.path.exists(path):
        path = filename + " (" + str(counter) + ")" + extension
        counter += 1

    return path
Run Code Online (Sandbox Code Playgroud)


unu*_*tbu 12

在某种程度上,Python具有内置于tempfile模块中的此功能.不幸的是,你必须使用私有全局变量tempfile._name_sequence.这意味着正式,tempfile不能保证在未来版本中_name_sequence甚至存在 - 它是一个实现细节.但是如果您无论如何都可以使用它,这将显示如何file#.pdf在指定的目录中创建表单的唯一命名文件,例如/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'))
Run Code Online (Sandbox Code Playgroud)


arb*_*zar 10

我试图在我的项目中实现同样的事情,但@unutbu 的回答对于我的需求来说似乎太“重”了,所以我最终想出了以下代码:

import os
index = ''
while True:
    try:
        os.makedirs('../hi'+index)
        break
    except WindowsError:
        if index:
            index = '('+str(int(index[1:-1])+1)+')' # Append 1 to number in brackets
        else:
            index = '(1)'
        pass # Go and try create file again
Run Code Online (Sandbox Code Playgroud)

以防万一有人偶然发现并需要更简单的东西。


las*_*tro 7

最近我遇到了同样的事情,这是我的方法:

import os

file_name = "file_name.txt"
if os.path.isfile(file_name):
    expand = 1
    while True:
        expand += 1
        new_file_name = file_name.split(".txt")[0] + str(expand) + ".txt"
        if os.path.isfile(new_file_name):
            continue
        else:
            file_name = new_file_name
            break
Run Code Online (Sandbox Code Playgroud)


小智 6

如果对所有文件进行编号都没有问题,并且您事先知道要写入的文件的名称,则可以简单地执行以下操作:

import os

counter = 0
filename = "file{}.pdf"
while os.path.isfile(filename.format(counter)):
    counter += 1
filename = filename.format(counter)
Run Code Online (Sandbox Code Playgroud)

  • 其中最优雅的一个! (2认同)

Bas*_*asj 6

假设您已经拥有这些文件:

在此输入图像描述

此函数通过在扩展名前添加 _1、_2、_3、... 后缀(如有必要)来生成下一个可用的非已存在文件名:

import os

def nextnonexistent(f):
    fnew = f
    root, ext = os.path.splitext(f)
    i = 0
    while os.path.exists(fnew):
        i += 1
        fnew = '%s_%i%s' % (root, i, ext)
    return fnew

print(nextnonexistent('foo.txt'))  # foo_3.txt
print(nextnonexistent('bar.txt'))  # bar_1.txt
print(nextnonexistent('baz.txt'))  # baz.txt
Run Code Online (Sandbox Code Playgroud)