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 moduleimport os#print the list of files and directories in current directoryprint("Before adding directory")print(os.listdir())print("\n")#create a directoryos.mkdir("./Educative", 0o755)print("After adding directory")#print the list of files and directories in current directoryprint(os.listdir())
Explanation
- Line 2: We import the
osmodule with methods likemkdirandlistdir. - Line 11: We create a directory named
Educativein the current directory./, and provide0o755as the mode.
We can check that the Educative directory is created in the output.