[英]A loop to increment a number if the file already exists in python
这是我试图实现这一目标的代码:
try:
os.mkdir(f'{path}')
with open(path + '\\SUSPENDED.txt', 'w') as file:
file.write('\n'.join(LIST))
except FileExistsError:
while FileExistsError:
i += 1
os.mkdir(f'{path}_{i}')
with open(path + '\\SUSPENDED.txt', 'w') as file:
file.write('\n'.join(LIST))
break
我期待的是,如果“路径”存在,则将其设为“路径_1”,如果“路径_1”存在,则将其设为“路径_2”,如果“路径_2”将其设为“路径_3”,依此类推...
对不起,如果我的问题不清楚
# 之后的所有解释都用代码编写:)
import os
target_path = os.path.abspath(os.path.dirname(__file__)) # Path where folder should be created.
base = 'tests' # Base name of the folder.
i = 0
while True:
try:
os.mkdir(base) # Try creating folder with base name.
except FileExistsError:
i += 1 # If folder exists increment an index.
base = base.split('_')[0] + f'_{i}' # Split the name by '_' and add index value.
else:
with open(os.path.join(target_path, base, 'SUSPENDED.txt'), 'w') as file: # Create file.
file.write('FOO') # Change content for anything you want.
break # Task completed, break the while loop :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.