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.
import os
os.makedirs(path,mode)
We need to import the os
module to use the makedirs()
method.
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.
#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"))
In the code above,
os
module which comes with methods like makedirs
mkdir
, listdir
, etc.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.