VOOZH about

URL: https://www.geeksforgeeks.org/python/python-os-mkdir-method/

⇱ os.mkdir() method-Python - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

os.mkdir() method-Python

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:

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

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


Output
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


Output
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

Comment