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
Before creating a single directory, our current directory looks like this:
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:
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.
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.
thanks