Last Updated : 11 Jul, 2025
os.mkdir() method in Python create a new directory at a specified path. If the directory already exists, a FileExistsError is raised. This method can also set permissions for the new directory using the optional mode parameter. Example:
Python
import os
d = "GeeksForGeeks"
parent_d = "/home/User/Documents"
path = os.path.join(parent_d, d)
os.mkdir(path)
print("Directory created at:", path)
Output
Directory created at: C:/Users/GFG0578/Documents\GeeksForGeeks
Explanation: This code creates a folder named GeeksForGeeks inside the specified parent directory. os.path.join() combines both paths correctly and os.mkdir() creates the new directory.
Syntax of os.mkdir()os.mkdir(path, mode=0o777, *, dir_fd=None)
Parameters:
Returns:
Example 1: Creating a directory with custom mode
Python
import os
d = "CustomFolder"
parent_path = "C:/Users/GFG0578/Documents"
mode = 0o755
path = os.path.join(parent_path, d)
os.mkdir(path, mode)
print("Directory created with mode:", oct(mode))
Output
Directory created with mode: 0o755
Explanation: This code creates a CustomFolder inside the given parent path with 0o755 permissions (Unix-based). oct(mode) displays the permissions in octal format.
Example 2: Handling errors if directory already exists
Python
import os
path = "C:/Users/GFG0578/Documents/ExistingFolder"
try:
os.mkdir(path)
except OSError as e:
print("Error:", e)
Error: [Errno 2] No such file or directory: 'C:/Users/GFG0578/Documents/ExistingFolder'
Explanation: This code attempts to create a directory that may already exist. To prevent the program from crashing, a try-except block catches any OSError, such as when the folder already exists and prints an appropriate error message.
Example 3: Invalid parent path
Python
import os
path = "C:/InvalidPath/NoFolder/NewDir"
try:
os.mkdir(path)
except OSError as e:
print("Error:", e)
Error: [Errno 2] No such file or directory: 'C:/InvalidPath/NoFolder/NewDir'
Explanation: This code tries to create a directory in a non-existent path. Since intermediate folders don't exist, os.mkdir() raises an OSError, which is caught and printed to prevent a crash.
Related Articles
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4