The os.mkdir() method in Python is used to create a new directory at a specified path. If the directory already exists, it raises a FileExistsError. The optional mode parameter can be used to specify permissions for the new directory.
import os
path = "GeeksForGeeks"
os.mkdir(path)
print("Directory created:", path)
Output
Directory created: GeeksForGeeks
Explanation: os.mkdir() creates a new directory named GeeksForGeeks at the specified path.
Syntax
os.mkdir(path, mode=0o777, *, dir_fd=None)
Parameters:
- path: Specifies the path of the directory to be created.
- mode: Specifies the permission mode for the directory. The default value is 0o777.
- dir_fd: Specifies a directory file descriptor for a relative path.
Return Value:
- Creates the specified directory and does not return a value.
- Raises FileExistsError if the directory already exists and OSError if the path is invalid or inaccessible.
Examples
Example 1: Create a Directory with Custom Mode
import os
path = "CustomFolder"
mode = 0o755
os.mkdir(path, mode)
print("Directory created with mode:", oct(mode))
Output
Directory created with mode: 0o755
Explanation:
- path specifies the directory name.
- mode = 0o755 specifies the directory permissions.
- os.mkdir() creates the directory with the given mode.
- oct(mode) displays the mode in octal format.
Example 2: Handle an Existing Directory
import os
path = "ExistingFolder"
os.mkdir(path)
try:
os.mkdir(path)
except FileExistsError:
print("Directory already exists.")
Output
Directory already exists.
Explanation:
- The first os.mkdir(path) creates the directory.
- The second os.mkdir(path) tries to create the same directory again.
- FileExistsError is raised because the directory already exists.
- The except block catches the error.
Example 3: Handling an Invalid Parent Path
import os
path = "InvalidPath/NewDir"
try:
os.mkdir(path)
except OSError as e:
print("Error:", e)
Output
Error: [Errno 2] No such file or directory: 'InvalidPath/NewDir'
Explanation:
- InvalidPath does not exist.
- os.mkdir() cannot create missing intermediate directories.
- An OSError is raised.
- The except block catches and prints the error.
Example 4: Creating a Directory in the Current Working Directory
import os
path = "NewFolder"
os.mkdir(path)
print("Directory created:", path)
Output
Directory created: NewFolder
Explanation:
- path specifies the name of the new directory.
- os.mkdir(path) creates the directory in the current working directory.
- The directory name is printed after creation.