循环内的mkdir

mkdir within a loop

我正在尝试在 Python 上创建多个目录,每个目录对应列表 loadcase_id_full 的每个元素,简单地定义为:[1, 2, 3, 4, 5]。

我尝试了以下方法:

import os
import yaml
from pathlib import Path
this_dir = Path(__file__).parent

top_dir = this_dir.parent

base_dir = top_dir / 'tmp'
with open(path_to_acc_matrix) as f:
    var = yaml.safe_load(f)

# Extracting the data in lists of a size equal to the number of load cases (usually 5)
loadcase_id_full = var['acceleration_matrix'][4]
path_to_new_dirs = top_dir / 'templates' / 'tests' / 'data'

path_iter = 1
path_iter = str(path_iter)
pathname = 'QS-' + path_iter
directory = path_to_new_dirs / pathname

for index in loadcase_id_full :
    if not os.path.exists(directory):
        os.makedirs(directory)
    path_iter = index
    path_iter = str(path_iter)
    pathname = 'QS-' + path_iter
    directory = base_dir / pathname

    print(directory)

这只会创建第一个目录(因此来自循环外定义的“目录”变量...) 打印功能告诉我我想要的路径是正确的:

/users/develop/tmp/QS-1
/users/develop/tmp/QS-2
/users/develop/tmp/QS-3
/users/develop/tmp/QS-4
/users/develop/tmp/QS-5

但它不会创建它们。如果我将 os.mkdirs 放在循环的末尾,它不会创建任何目录。有谁知道如何解决这个问题?

在此先感谢您的帮助! :)

这是代码的简化版本,希望能避免混淆并满足创建多个目录的需要。

from pathlib import Path


top_dir = Path('ENTER YOUR DATA PATH HERE')
base_dir = Path('ENTER YOUR BASE PATH HERE')
loadcase_id_full = ['ENTER YOUR LIST VALUES HERE', '...']

path_to_new_dirs = top_dir / 'templates' / 'tests' / 'data'
path_to_new_dirs.mkdir(exist_ok=True, parents=True)

for index in loadcase_id_full:
    directory = base_dir / f'QS-{index}'
    print(directory)
    directory.mkdir(exist_ok=True, parents=True)