[英]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.