Mastering Nested Directory Creation in Python
Understanding the Basics
To create a nested directory in Python, you need to have a solid grasp of Python directory and file management, Python modules, and Python exception handling. With these fundamentals in place, you’re ready to dive into the world of nested directory creation.
The Power of pathlib.Path.mkdir (Python 3.5 and above)
When working with Python 3.5 and above, the pathlib library offers a convenient way to create nested directories using Path.mkdir
. Here’s how it works:
from pathlib import Path
# Create a nested directory
Path('/path/to/directory').mkdir(parents=True, exist_ok=True)
By default, parents
is set to False
. If the parent directory doesn’t exist, a FileNotFoundError
is thrown. To avoid this, set parents
to True
.
exist_ok
is also set to False
by default. If the directory already exists, a FileExistsError
is raised. Set exist_ok
to True
to prevent this error.
A Simple Alternative: os.makedirs (Python 3.2 and above)
For Python 3.2 and above, the os module provides a straightforward way to create nested directories using makedirs()
. Here’s the lowdown:
import os
# Create a nested directory
os.makedirs('/path/to/directory', exist_ok=True)
Remember to provide the full path (absolute path) of the directory, not the relative path.
Another Option: distutils.dir_util
This approach is similar to using os.makedirs()
. Here’s what you need to know:
from distutils.dir_util import mkpath
# Create a nested directory
mkpath('/path/to/directory')
Provide the full path (absolute path) of the directory, not the relative path.
Raising an Exception if the Directory Already Exists
What if you want to raise an exception if the directory already exists? Here’s how:
try:
os.makedirs('/path/to/directory')
except FileExistsError:
print("Directory already exists")
Additional Tips and Tricks
- Remember, when creating nested directories, always provide the full path (absolute path) of the directory, not the relative path.
- And, if the directory already exists, the code won’t raise an exception.
Further Reading
Want to learn more about working with directories in Python? Check out our article on Python Program to Get the Full Path of the Current Working Directory.