EN
Python - create directory with subdirectory
3
points
In this article, we would like to show you how to create directory with a subdirectory in Python.
Quick solution:
from pathlib import Path
Path("C:\\example_directory\example_subdirectory").mkdir(parents=True, exist_ok=True)
Note:
The
exist_okparameter was added in Python 3.5. Set it onTrueso you won't getFileExistsErrorif the directory exists.
Practical example
In this example, we use Path.mkdir() method from pathlib module to create a nested directory.
from pathlib import Path
Path("C:\\some_path\example_directory\example_subdirectory").mkdir(parents=True, exist_ok=True)
Result:
Solution for Python ≤ 3.5
In this example, we use makedirs() method from os module to create a nested directory.
import os
directory = "C:\\example_path\example_directory\example_subdirectory"
if not os.path.exists(directory):
os.makedirs(directory)