How to Create Directory in Python

Muhammad Waiz Khan Feb 02, 2024
  1. Create Directory in Python Using the path.exists() and makedirs() Methods of the os Module
  2. Create Directory in Python Using the Path.mkdir() Method of the pathlib Module
How to Create Directory in Python

This tutorial will explain various methods to check if a directory exists and how to create the directory if it does not exist. Suppose we want to save a file in a specific path like C:\myfolder\myfile.txt, if the myfolder exists, the myfile.txt should be saved there, and if not, we want first to create the myfolder directory and then save the file in it. We can use the following methods in Python to achieve this goal.

Create Directory in Python Using the path.exists() and makedirs() Methods of the os Module

The path.exists() method checks if the given path exists and returns True if it exists and False otherwise. The makedirs() takes the path as input and creates the missing intermediate directories in the path.

The code example below demonstrates how to check the existence of the directory and create it if it does not exist in Python:

import os

if not os.path.exists("parentdirectory/mydirectory"):
    os.makedirs("parentdirectory/mydirectory")

We can also use the try ... except statement with the makedirs() method to check the existence and otherwise create the directory.

try:
    os.makedirs("parentdirectory/mydirectory")
except FileExistsError:
    pass

Create Directory in Python Using the Path.mkdir() Method of the pathlib Module

The Path.mkdir() method, in Python 3.5 and above, takes the path as input and creates any missing directories of the path, including the parent directory if the parents flag is True. The Path.mkdir will return the FileNotFoundError if the parent directory is missing if the parents flag is False, but will still create the intermediate directories. exist_OK is False by default, meaning it raises FileExistsError if the given directory already exists. When exist_OK is True, it will ignore FileExistsError.

To check if the directory exists and create it if it does not exist, we need to pass the directory path to the Path.mkdir() method while setting the required flags True. The example code below demonstrates how to use the Path.mkdir() for this task.

from pathlib import Path

path = Path("parentdirectory/mydirectory")
path.mkdir(parents=True, exist_ok=True)

Related Article - Python Directory