How to run os.mkdir() with -p option in Python? How to run os.mkdir() with -p option in Python? python python

How to run os.mkdir() with -p option in Python?


You can try this:

# top of the fileimport osimport errno# the actual codetry:    os.makedirs(directory_name)except OSError as exc:     if exc.errno == errno.EEXIST and os.path.isdir(directory_name):        pass


According to the documentation, you can now use this since python 3.2

os.makedirs("/directory/to/make", exist_ok=True)

and it will not throw an error when the directory exists.


Something like this:

if not os.path.exists(directory_name):    os.makedirs(directory_name)

UPD: as it is said in a comments you need to check for exception for thread safety

try:    os.makedirs(directory_name)except OSError as err:    if err.errno!=17:        raise