Python os.mkdir() Method

Python os.mkdir() method is used to create a single directory at the specified path.

It creates a directory named path with the specified mode. The mode specifies the directory’s permissions but is modified by the process’s umask value.

Unlike os.makedirs(), os.mkdir() can only create one directory simultaneously. It will not create intermediate directories if they don’t exist, and doing so will result in a FileNotFoundError.

Syntax

os.mkdir(path, mode = 0o777, *, file_descriptor = None)

Parameters

Name Description
path (string) It is a path where the new directory will be created.
mode (optional) The mode of the directory to be created. The default mode is 0o777 (octal), allowing read, write, and execute permission for the owner, group, and others. The current umask value is first masked out.
file_descriptor (optional) It is a file descriptor referring to a directory.

Return value

This method does not return any value.

Example 1: Creating a single directory

Understanding of Python os.mkdir() Method

Before creating a single directory, our current directory looks like this:

Screenshot before creating a directory

import os

path = '/Users/krunallathiya/Desktop/Code/pythonenv/env/newdir/maindir'

os.mkdir(path)

print("Directory created at:", path)

Output

Directory created at: /Users/krunallathiya/Desktop/Code/pythonenv/env/newdir/maindir

After creating a single directory:

Output of os.mkdir() Method

Example 2: Handling errors when creating a directory

import os

path = '/Users/krunallathiya/Desktop/Code/pythonenv/env/newdir/maindir'

try:
  os.mkdir(path)
  print("Directory created at:", path)
except FileExistsError:
  print("Directory already exists.")
except FileNotFoundError:
  print("Parent directory does not exist.")

Output

Directory already exists.

Here, the code handles FileExistsError when trying to create a directory.

1 thought on “Python os.mkdir() Method”

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.