Function
os.mkdir(path, mode=0o777, *, dir_fd=None)
Overview
- The function os.mkdir() creates a directory at the specified path in the filesystem.
- Unlike the os.makedirs() function, the os.mkdir() creates only the leaf directory specified in a given path. The os.makedirs() creates all the directories specified in a path recursively.
- When the leaf directory already exists in the filesystem the function mkdir() raises a FileExistsError.
- The examples create directory using both absolute and relative paths and print the directory information using the os.stat() function.
Parameters
path - The path of the directory to be created.
mode - Optional parameter specifying user, group and other permissions. Default value is 0o777.
dir_fd - Descriptor denoting the relative path of the directory to be created. Default value is None.
Return Value
None
Exceptions
FileNotFoundError - When the parent directory does not exist FileFileNotFoundError is raised.
FileExistsError - When the directory with the same name as the new directory to be created
exists a FileExistsError is raised.
Example 1 - Create a directory using absolute path
# Example Python program to create a
# directory in a given path using the function
# os.mkdir
import os
path = "/Ex/Notes"
permissions = 0o755
try:
# Create the directory
os.mkdir(path, mode = permissions)
except FileExistsError as err:
print(err)
print("Directory information for %s:"%path)
# Print information about the directory
# In case of a FileExistsError the stat is
# for the already existing directory
dirInfo = os.stat(path)
print(dirInfo)Output
Directory information for /Ex/Notes:
os.stat_result(st_mode=16877, st_ino=8600031, st_dev=16777220, st_nlink=2, st_uid=0, st_gid=0, st_size=64, st_atime=1684227964, st_mtime=1684227964, st_ctime=1684227964)Example 2 - Create a directory using relative path and its directory descriptor
# Example Python program that creates a
# directory relative to the one specified
# by a directory descriptor(i.e.,File descriptor
# of the directory)
import os
dirPath = "/PythonProgs"
dirName = "Fonts"
permissions = 0o755
# Get the directory descriptor of the path
dirFd = os.open(dirPath, os.O_APPEND, 0o755)
try:
# Create the directory relative to the one
# specified by the directory descriptor
os.mkdir(dirName, mode = permissions, dir_fd = dirFd)
except FileExistsError as err:
print(err)
print("Directory info for %s:"%(dirPath + "/" + dirName))
# Print info about the directory
dirInfo = os.stat(dirPath + "/" + dirName)
print(dirInfo)Output
Directory info for /PythonProgs/Fonts:
os.stat_result(st_mode=16877, st_ino=8683605, st_dev=16777220, st_nlink=2, st_uid=0, st_gid=0, st_size=64, st_atime=1684315151, st_mtime=1684315151, st_ctime=1684315151)