Python Forum
Folders in folders - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Folders in folders (/thread-26279.html)



Folders in folders - jenost - Apr-26-2020

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!


RE: Folders in folders - buran - Apr-26-2020

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))



RE: Folders in folders - DeaD_EyE - Apr-26-2020

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?


RE: Folders in folders - buran - Apr-26-2020

@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.


RE: Folders in folders - DeaD_EyE - Apr-26-2020

I edited my post a litte bit.


RE: Folders in folders - jenost - Apr-26-2020

Great! I will try this - Thanks!