如果名称存在,如何创建带有“01”的文件?

How to create a file with '01' if name exists?

open() 内置函数中是否有一个特定的参数,以便如果文件名已经存在,它会通过在文件名后添加一个数字来创建一个文件??

这样,如果 "file.txt" 存在,它会自动创建 "file-01.txt"

或任何其他解决方案。!

不,我不认为有这样的事情,但你可以使用 os.path.isfile 自己做:

import os
filename = "yourFileName.txt"
if os.path.isfile(filename): #check if filename exists in the directory
    filename = filename.split(".")[:-1] + "-01" + filename.split(".")[-1]
with open(filename, "w+") as f:
    f.write(yourString)

是这样的吗?

import os
if os.path.exists(filename):
   fileparts = filename.split('.')
   filename = fileparts[0] + '01.'
   for a in fileparts[1:]:
     filename += a

我已经找到解决办法了,谢谢!!

b = True
c = 1
while b:
    f_name = 'Task-{:02.0f}.txt'.format(c)
    try:
        f = open(f_name,'x')
        b = False
    except FileExistsError:
        c += 1
f.close()

看看你对此有何看法。 ......这就是我用来做你正在寻找的东西。这是我之前找到的解决问题的最小方法,并且很容易包装成一个函数:

import os

name = 'blah.txt'

uniq_name = name
while os.path.isfile(uniq_name):
    # if increment variable 'delta' isn't defined, make it 1.  Otherwise increment
    delta = delta+1 if 'delta' in vars() else 1
    uniq_name = f'{os.path.splitext(name)[0]}-{delta}{os.path.splitext(name)[1]}'

# this you don't need - it's just equivalent to a 'touch' command to show
# the output
open(uniq_name, 'a').close()