判断文件夹是否存在,并创建。
The directory path is based on several variables including the environment name, scenario name, algorithm name, and experiment name. If the directory does not exist, it creates it. If there are existing directories, it selects the next available number and adds "run" to the beginning of the folder name. Finally, it sets the process title to include information about the algorithm, environment, experiment, and user.
这个目录的路径是基于环境的名字、场景的名字、算法的名字和实验的名字等一系列变量,这段代码是判断中是否存在run_dir这个目录路径:
- 如果不存在,则创建这个名为
run_dir的文件夹。 - 如果存在,则判断是第几次实验,例如已经是第7次实验,则会存在一个
run7的文件夹,此时为了执行新的实验,则创建一个新的文件夹run8。
from pathlib import Path
# run dir
run_dir = (
Path(os.path.split(os.path.dirname(os.path.abspath(__file__)))[0] + "/results")
/ all_args.env_name
/ all_args.scenario_name
/ all_args.algorithm_name
/ all_args.experiment_name
)
if not run_dir.exists():
os.makedirs(str(run_dir))
if not run_dir.exists():
curr_run = "run1"
else:
exst_run_nums = [
int(str(folder.name).split("run")[1])
for folder in run_dir.iterdir()
if str(folder.name).startswith("run")
]
if len(exst_run_nums) == 0:
curr_run = "run1"
else:
curr_run = "run%i" % (max(exst_run_nums) + 1)
run_dir = run_dir / curr_run
if not run_dir.exists():
os.makedirs(str(run_dir))
setproctitle.setproctitle(
str(all_args.algorithm_name)
+ "-"
+ str(all_args.env_name)
+ "-"
+ str(all_args.experiment_name)
+ "@"
+ str(all_args.user_name)
)
以下是chatgpt生成的类似的解决方案:
import os
dir_path = "path/to/directory" # 替换成你想要查找的目录路径
prefix = "example"
suffix = ""
# 检查是否存在第一个文件
filename = f"{prefix}{suffix}"
if not os.path.isfile(os.path.join(dir_path, filename)):
print(f"找不到文件:{filename}")
else:
# 获取最后一个文件
i = 0
while True:
filename = f"{prefix}{i}{suffix}"
if not os.path.isfile(os.path.join(dir_path, filename)):
last_file = f"{prefix}{i-1}{suffix}"
print(f"最后一个文件是:{last_file}")
break
i += 1

浙公网安备 33010602011771号