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 is0o777.
Let’s take a look at an example.
Example
#import the os modulefrom os import listdir, makedirs#print the list of files and directories in current directoryprint("Before adding directory")print(listdir())print("\n")#create a directorymakedirs("./Educative/Leaf", 0o755)print("After adding directory")#print the list of files and directories in current directoryprint(listdir())print("\n")print("Display inner directory")print(listdir("./Educative"))
Explanation
In the code above,
- In line 2, we import the
osmodule which comes with methods likemakedirsmkdir,listdir, etc. - In line 11, we create directories with the names
EducativeandLeafin the current directory./, and we provide mode as0o755. This will first create theEducativedirectory and then createLeafinside it.
In the output, we can check that the directories Educative and Leaf are created.