![]() |
VOOZH | about |
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:
Output
Directory created at: C:/Users/GFG0578/Documents\GeeksForGeeksExplanation: 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.
os.mkdir(path, mode=0o777, *, dir_fd=None)
Parameters:
Returns:
Example 1: Creating a directory with custom mode
Output
Directory created with mode: 0o755Explanation: 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
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
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