In Python, you can create a directory using the os module or the pathlib module. Here’s how to create a directory using both methods:
Using os module:
The os.mkdir() function creates a single directory. If the directory already exists, it raises an error. To avoid this, you can use os.makedirs() which creates intermediate directories as needed.
Example:
python
import os
# Create a single directory
os.mkdir(“new_directory”)
# Create intermediate directories if needed
os.makedirs(“parent_directory/new_directory”, exist_ok=True)
In this example, exist_ok=True prevents an error if the directory already exists.
Using pathlib module:
pathlib offers an object-oriented approach to handle file system paths. The Path class provides a mkdir() method to create directories.
Example:
python
from pathlib import Path
# Create a directory
path = Path(“new_directory”)
path.mkdir(exist_ok=True)
This method works similarly, and exist_ok=True ensures no error occurs if the directory exists