Python Forum

Full Version: Folders in folders
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi!
Trying to create three different sub-folders named: "raw" "right" and "left" in one folder named from a txt file. I succeeded to make one sub-folder, "raw" in each.

import os
path = '/raw'
with open('regina.txt') as x:
    for line in x:
        line = line.strip()
        os.makedirs(line + path) 
Would appreciate tips on how to think/ solve this. Think
Thanks in advance!
use a for loop to iterate over folders you want to create. Also use os.path.join to create paths

import os
sub_folders = ('raw', 'right', 'left')
with open('regina.txt') as x:
    for line in x:
        line = line.strip()
        for sub_folder in sub_folders:
            os.makedirs(os.path.join(line, sub_folder))
from pathlib import Path


path = Path('/raw')
with open('regina.txt') as fd:
    for subdir in fd:
        subdir = subdir.strip()
        (path / subdir).mkdir(parents=True, exist_ok=True)
This creates the Paths /raw/{line_in_regina.txt} ...
This creates also the parent path raw. If a directory already exists (exist_ok=True), then it's continuing without any error.
The os.path is old style, pathlib has many convenient methods.

If the names of the folders should be in ('raw', 'right', 'left'), then the code is a bit different.

from pathlib import Path

pasths = ('raw', 'right', 'left')
with open('regina.txt') as fd:
    for path in paths:
        for subdir in fd:
            subdir = subdir.strip()
            Path(path, subdir).mkdir(parents=True, exist_ok=True)
This will create the directories ('raw', 'right', 'left') and will create in each directory the subdirectories from regina.txt.
Is that what you want?
@DeaD_EyE - they want to read the parent folder(s) from text file and then create 3 subfolders - raw, right, left

EDIT: @DeaD_EyE changed their code according to OP question.
I edited my post a litte bit.
Great! I will try this - Thanks!