pynovice pynovice - 1 month ago 6
Python Question

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

I want to run

mkdir
command as:

mkdir -p directory_name


What's the method to do that in Python?

os.mkdir(directory_name [, -p]) didn't work for me.

Answer

You can try this:

# top of the file
import os
import errno

# the actual code
try:
    os.makedirs(directory_name)
except OSError as exc: 
    if exc.errno == errno.EEXIST and os.path.isdir(directory_name):
        pass
    else:
        raise