Creating Directories with mkdir() Functionality in Python
The widely-used Unix and Windows command line utility mkdir offers a highly convenient -p flag, which enables the creation of nested directories. For those working within the Python programming language, a similar functionality can be achieved natively, obviating the need for external system calls.
Python 3.5 and Above: pathlib.Path.mkdir
In Python versions 3.5 and later, the pathlib.Path.mkdir method provides a straightforward solution. The following snippet illustrates its usage with the exist_ok parameter:
<code class="python">import pathlib path = "/tmp/path/to/desired/directory" pathlib.Path(path).mkdir(parents=True, exist_ok=True)</code>
Python 3.2 to 3.4: os.makedirs
For Python versions between 3.2 and 3.4, os.makedirs can be employed with the exist_ok argument:
<code class="python">import os path = "/tmp/path/to/desired/directory" os.makedirs(path, exist_ok=True)</code>
Python 2.5 to 3.1: Handling Errors in os.makedirs
In earlier Python versions (2.5 to 3.1), the following approach handles errors encountered with os.makedirs:
<code class="python">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 else: raise</code>
The above is the detailed content of How to Create Nested Directories in Python: A Guide for All Versions. For more information, please follow other related articles on the PHP Chinese website!