Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
communitycreator

What is os.makedirs() in Python?

Gutha Vamsi Krishna

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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.

RELATED TAGS

python
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring