Search code examples
pythonmkdir

mkdir within a loop


I am trying to create multiple directories on Python, one for each of the elements of the list loadcase_id_full defined simply by : [1, 2, 3, 4, 5].

I tried the following:

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)

This only creates the first directory (so from the "directory" variable defined outside of the loop...) The print function shows me that the paths I want are correct:

/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

But it just doesn't create them. If I put the os.mkdirs at the end of the loop, it doesn't create any directories. Does anyone knows how to solve this?

Thanks in advance for your help! :)


Solution

  • Here's a simplified version of the code that hopefully avoids confusion and gets to the need of creating multiple directories.

    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)