makedirs() function of os module in Python

The makedirs() function of os module in Python creates a given directory hierarchy and the leaf directory recursively.

Os Updated 13 May 2023 1 min read

Function

os.makedirs(name, mode=0o777, exist_ok=False)

Overview

  • The function makedirs() creates a leaf directory and its parent directories recursively in the filesystem.

  • While the mkdir() function of os module creates a single directory in the filesystem, the makedirs() creates a directory hierarchy including a specified leaf directory.

Parameters

name - The path of the leaf directory.

mode - Optional parameter. The default value is 0o777, which means all directories created along with the leaf directory will have Read, Write and Execute permissions for User, Group and others.

exist_ok - If True, when the function finds an existing directory along the path it continues creating the remaining directories. If False, a FileExistsError is raised when an existing directory is found.

Return Value

None

Example

python
# Example Python program that creates

            # the leaf directory and all the intermediate

            # parent directories recursively

            import os

# Leaf directory and its path

            leafDirPath = "./l1/l2/l3"

# Create parent directories and leaf directory

            os.makedirs(leafDirPath, mode=0o741, exist_ok=True)

# Do a walk() and descend the hierarchy

            entries = os.walk("./l1")

# Print the contents of each directory

            for entry in entries:

                print(entry)

Output

Output
('./l1', ['l2'], [])

            ('./l1/l2', ['l3'], [])

            ('./l1/l2/l3', [], [])