Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.")
like image 747
Pewniaczek Avatar asked Mar 03 '26 06:03

Pewniaczek


1 Answers

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.

like image 180
Mohammad Khoshbin Avatar answered Mar 04 '26 20:03

Mohammad Khoshbin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!