Search code examples
pythonlistdirectorynested-loops

Creating directories with OS module


Hi there I'm trying to create a small tool that will create child directory's within the Root directory

Root Dir(python) And child Dir(DS, WEB, Flask, Learn) stuff like that

At starting I have done it statically Here is the Code

import os

web = "Web"
Ds = "Data-structures"
Learn = "Learn"
tools = "Tools"

list1 = []
var = int(input("Enter number of Dir:- "))
for x in range(0, var):
    Lang = input("Enter Lang:- ")
    list.append(Lang)


for i in list1:
    os.system(
        f'mkdir {i} && cd {i} && mkdir {web} && mkdir {Ds} && mkdir {Learn} && mkdir {tools}')

Then I decided to do it dynamically By using two lists just like before but thing's don't go well Here is the code

import os

A = int(input("Enter number of dirs to be in A Specific languge(Ex:1 or 2):- "))
list1 = []
for x in range(0, A):
    B = input("Enter the Dir name(Ex:- DS, Web..etc):- ")
    list.append(B)
print(list)


C = int(input("Enter number of languages to be In the Dir(Ex:1 or 2):- "))
list2 = []
for x in range(0, C):
    D = input("Enter languges Name(Ex:- python,php,Golang):- ")
    list2.append(D)


for i, j in zip(list2, list1):
    os.system(f'mkdir {i} && cd {i} && mkdir {j} && mkdir {j}')
#tried all combination that I know
#for i in range(0,lis1):
#    for j in list2:
#        os.system(f'mkdir {list2} && cd {list2} && {os.mkdir(list1[i])}')

So I do Some try on it by using nested for loop or while loop but I didn't get an answer for what I did at the second code, I won't be able to give for k in range(0, A): if I give it's throwing me Error A subdirectory or file py already exists. And it is obvious to Get the Error like I'm recreating the same content, again and again, using for loop

What I want is to create Root:-Python child's:-Web, DS..etc

You don't want to use the same code if you know other ways Please Do let me Know

Please, anyone, Help me


Solution

  • To prompt the user, you can create a small function which ask for the user to enter values in order.

    For example:

    def ask_values(prompt, input_msg):
        choices = []
        print(f"{prompt} (press <ENTER> when finished)")
        while True:
            choice = input(input_msg)
            if choice:
                choices.append(choice)
            else:
                return choices
    

    This function will loop indefinitely until the user press <ENTER>, and then return the values.

    You can then use this function twice: for the directories and for the languages:

    directories = ask_values(
        "Enter the directories",
        "Enter the directory name (ex.: DS, Web, etc.): "
    )
    print("=> directories:", directories)
    print()
    
    languages = ask_values(
        "Enter the languages",
        "Enter the language name (ex.: python, php, go, etc.): "
    )
    print("=> languages:", languages)
    print()
    

    Then, you need to loop over the directories and the languages to create the tree structure. Don't forget to specify the full path of the root directory in a global variable (for instance):

    NOTE: in this demonstration, I choose the current working directory: "."

    Solution 1: using os module:

    import os
    
    # Root directory of you directory tree
    root_dir = os.path.abspath(".")
    
    print("Creating directories...")
    for dir_name in directories:
        for lang in languages:
            path = os.path.join(root_dir, dir_name, lang)
            try:
                os.makedirs(path)
            except FileExistsError:
                pass
    print("Done.")
    

    Solution 2: using pathlib module

    import pathlib
    
    # Root directory of you directory tree
    root_dir = pathlib.Path(".").absolute()
    
    print("Creating directories...")
    for dir_name in directories:
        for lang in languages:
            path = root_dir.joinpath(dir_name, lang)
            path.mkdir(parents=True, exist_ok=True)
    print("Done.")