Makedirs() Function Of Os Module In Python

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:

# 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:

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

 


Copyright 2023 © pythontic.com