What is os.makedirs() in Python?

Overview

The os.makedirs() method is used to create a directory recursively in the os module using Python. It is similar to the method os.mkdir() with the addition that it also creates intermediate directories to create leaf directories.

Syntax

import os
os.makedirs(path,mode)

We need to import the os module to use the makedirs() method.

Parameters

We will pass the following parameters to the os.makedirs() method:

  • path: This provides the path including the directories’ names to be created.
  • mode: This provides the mode for the directory. By default, it is 0o777.

Let’s take a look at an example.

Example

#import the os module
from os import listdir, makedirs
#print the list of files and directories in current directory
print("Before adding directory")
print(listdir())
print("\n")
#create a directory
makedirs("./Educative/Leaf", 0o755)
print("After adding directory")
#print the list of files and directories in current directory
print(listdir())
print("\n")
print("Display inner directory")
print(listdir("./Educative"))

Explanation

In the code above,

  • In line 2, we import the os module which comes with methods like makedirs mkdir, listdir, etc.
  • In line 11, we create directories with the names Educative and Leaf in the current directory ./, and we provide mode as 0o755. This will first create the Educative directory and then create Leaf inside it.

In the output, we can check that the directories Educative and Leaf are created.

Free Resources