patternpythonCriticalCanonical
mkdir -p functionality in Python
Viewed 0 times
functionalitymkdirpython
Problem
Is there a way to get functionality similar to
mkdir -p on the shell from within Python. I am looking for a solution other than a system call. I am sure the code is less than 20 lines, and I am wondering if someone has already written it?Solution
For Python ≥ 3.5, use
The
For Python ≥ 3.2,
For even older versions of Python, you can use
pathlib.Path.mkdir:import pathlib
pathlib.Path("/tmp/path/to/desired/directory").mkdir(parents=True, exist_ok=True)The
exist_ok parameter was added in Python 3.5.For Python ≥ 3.2,
os.makedirs has an optional third argument exist_ok that, when True, enables the mkdir -p functionality—unless mode is provided and the existing directory has different permissions than the intended ones; in that case, OSError is raised as previously:import os
os.makedirs("/tmp/path/to/desired/directory", exist_ok=True)For even older versions of Python, you can use
os.makedirs and ignore the error:import errno
import os
def mkdir_p(path):
try:
os.makedirs(path)
except OSError as exc: # Python ≥ 2.5
if exc.errno == errno.EEXIST and os.path.isdir(path):
pass
# possibly handle other errno cases here, otherwise finally:
else:
raiseCode Snippets
import pathlib
pathlib.Path("/tmp/path/to/desired/directory").mkdir(parents=True, exist_ok=True)import os
os.makedirs("/tmp/path/to/desired/directory", exist_ok=True)import errno
import os
def mkdir_p(path):
try:
os.makedirs(path)
except OSError as exc: # Python ≥ 2.5
if exc.errno == errno.EEXIST and os.path.isdir(path):
pass
# possibly handle other errno cases here, otherwise finally:
else:
raiseContext
Stack Overflow Q#600268, score: 1449
Revisions (0)
No revisions yet.