What is os.mkdir() in Python?

Overview

Python’s os module comes with the mkdir() method that creates a directory in the system.

Syntax

import os
os.mkdir(path,mode)

Import the os module to use the mkdir() method.

Parameters

The method os.mkdir() will accept two parameters as follows:

  • path: It accepts the path as a parameter and creates a directory with the name present at the end of the path.
  • mode: We provide the mode for the directory here. By default, it is 0o777.

Let’s look at an example.

Example

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

Explanation

  • Line 2: We import the os module with methods like mkdir and listdir.
  • Line 11: We create a directory named Educative in the current directory ./, and provide 0o755 as the mode.

We can check that the Educative directory is created in the output.

Free Resources