Languages
[Edit]
EN

Python - create directory with subdirectory

3 points
Created by:
Molly
231

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_ok parameter was added in Python 3.5. Set it on True so you won't get FileExistsError if 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:

Python - create directory with subdirectory - before
Python - create directory with subdirectory - before
Python - create directory with subdirectory - after
Python - create directory with subdirectory - after

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)

Alternative titles

  1. Python - create nested directory
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Python - file operations

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join