Python os.mkdir() Method
os.mkdir() Overview
The os.mkdir() method is used to create directories in numeric permission mode. The default mode is 0777 (octal).
If the directory has multiple levels, the last level is created, and an OSError is thrown if there is a non-existent parent directory to the last level.
os.mkdir() Syntax
The syntax format of the mkdir() method is as follows.
os.mkdir(path[, mode])
os.mkdir() Parameters
- path – The directory to be created, either relative or absolute path.
- mode – the numeric mode of permissions to be set for the directory
os.mkdir() Return Value
This method has no return value.
os.mkdir() Demo#1
The following example demonstrates the use of the mkdir() method.
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import os, sys
# Created directories
path = "/root/aaa/bbb/ccc/ddd"
os.mkdir(path, 755)
print ("Directory created!!!")
Output:
os.mkdir() Demo#2
Errors while using os.mkdir() method.
if directory / file that is to be created already exists then ‘FileExistsError’ will be raised by os.mkdir() method.
Similarly, if the specified path is invalid ‘FileNotFoundError’ Error will be raised.
# Python program to explain os.mkdir() method
# importing os module
import os
# Directory
directory = "apidemos"
# Parent Directory path
parent_dir = "/root/eee"
# Path
path = os.path.join(parent_dir, directory)
# Create the directory
# 'apidemos' in
# '/root/eee'
os.mkdir(path)
print("Directory '%s' created" %directory)
Output:
os.mkdir() Demo#3
Handling error while using os.mkdir() method
# Python program to explain os.mkdir() method
# importing os module
import os
# path
path = '/root/eee/apidemos'
# Create the directory
# 'apidemos' in
# '/root/eee/'
try:
os.mkdir(path)
except OSError as error:
print(error)
output: