[英]How to create a file with '01' if name exists?
Is there a specific argument in open() built-in function so that if the filename already exists, it creates a file by adding a number to its name?? open() 内置 function 中是否有特定参数,以便如果文件名已经存在,它会通过在文件名中添加数字来创建文件?
such that if "file.txt" exists, it automatically creates "file-01.txt"这样如果“file.txt”存在,它会自动创建“file-01.txt”
Or any other solution.!或任何其他解决方案。!
No, I don't think there's something like this but you can do it yourself using os.path.isfile
:不,我不认为有这样的事情,但你可以使用
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)
Something like this?像这样的东西?
import os
if os.path.exists(filename):
fileparts = filename.split('.')
filename = fileparts[0] + '01.'
for a in fileparts[1:]:
filename += a
I have found a solution, Thanks!!我找到了解决办法,谢谢!!
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()
See what you think of this.看看你对此有何看法。 ...this is what I use to do what you're looking for.
...这就是我用来做你正在寻找的东西。 It's the smallest way I found to solve the problem before, and is easy to wrap into a function:
这是我之前发现的解决问题的最小方法,并且很容易包装成 function:
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.