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:
- path (str, bytes or os.PathLike): Target directory path.
- mode (int, optional): Permission (default: 0o777).
- dir_fd (optional): Relative directory file descriptor; ignored if path is absolute.
Returns:
- This function performs the operation but does not return a value.
- Raises FileExistsError if the directory already exists or OSError if the path is invalid or inaccessible.
Examples
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)
OutputError: [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)
OutputError: [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
Explore
Python Fundamentals
Python Data Structures
Advanced Python
Data Science with Python
Web Development with Python
Python Practice