pythondirectorysubdirectory

Checking folder and if it doesn't exist create it


I am quite new to python so I need some help. I would like to create a code that checks if a folder with a given name is created, if not, it creates it, if it exists, goes to it and in it checks if there is another folder with a given name, if not, it creates it. In my code I don't know how to go to folder that already exist or has just been created and repeat IF.

import os


MYDIR = ("test")
CHECK_FOLDER = os.path.isdir(MYDIR)


if not CHECK_FOLDER:
    os.makedirs(MYDIR)
    print("created folder : ", MYDIR)

else:
    print(MYDIR, "folder already exists.")

Solution

  • If you want to create a folder inside a second folder or check the existence of them you can use builtin os library:

    import os
    
    PATH = 'folder_1/folder_2'
    if not os.path.exists(PATH):
        os.makedirs(PATH)
    

    os.makedirs() create all folders in the PATH if they does not exist.