5

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.")
Pewniaczek
  • 81
  • 1
  • 1
  • 5
  • Does this answer your question? [How can I safely create a nested directory?](https://stackoverflow.com/questions/273192/how-can-i-safely-create-a-nested-directory) – hamagust Feb 23 '22 at 17:02

4 Answers4

12

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.

9

os has an inbuilt method for this, you can simply do: os.makedirs("dir", exist_ok=True). This will basically create a folder if it does not exist and do nothing if the folder already exists.

Documentation: https://docs.python.org/3/library/os.html#os.makedirs

veedata
  • 1,048
  • 1
  • 9
  • 15
1
#!/usr/bin/python
import os
directory0="directory0"
## If folder doesn't exists, create it ##
if not os.path.isdir(directory0):
    os.mkdir(directory0)
Vadim Chernetsov
  • 370
  • 1
  • 2
  • 14
0

You can use os import or pathlib to manage your path (example: to know if your path is a dir, if exist ...)

The os import have OS dependent features, so I recommend to use pathlib.

If you check on google you will find lot of example like:

https://www.guru99.com/python-check-if-file-exists.html

https://www.geeksforgeeks.org/create-a-directory-in-python/