Python | os.mkdir() method (original) (raw)

Last Updated : 16 Jan, 2024

All functions in the OS module raise **OSError in the case of invalid or inaccessible file names and paths, or other arguments that have the correct type, but are not accepted by the operating system.

os.mkdir() method in Python is used to create a directory in Python or create a directory with Python named path with the specified numeric mode. This method raises FileExistsError if the directory to be created already exists.

os.mkdir() Syntax in Python

**Syntax: os.mkdir(path, mode = 0o777, *, dir_fd = None)

*Parameter _*:**_

**Return Type: This method does not return any value.

os.mkdir() method Examples

There are various uses ways of os.mkdir() to create a directory in Python or create a directory with Python using os.mkdir, Here we are discussing some general examples of creating a directory in Python or creating a directory with Python those are following.

Create Directory In Python

In this example code uses os.mkdir() to Python create folder two directories: “GeeksForGeeks” and “ihritik” in the “/home/User/Documents” directory. The first directory is created with default permissions, while the second one is created with specified permissions (mode 0o666).

Python3

import os

directory = "GeeksForGeeks"

parent_dir = "/home/User/Documents"

path = os.path.join(parent_dir, directory)

os.mkdir(path)

print ( "Directory '%s' created" % directory)

directory = "ihritik"

parent_dir = "/home/User/Documents"

mode = 0o666

path = os.path.join(parent_dir, directory)

os.mkdir(path, mode)

print ( "Directory '%s' created" % directory)

Output

Directory 'GeeksForGeeks' created Directory 'ihritik' created

Errors while using os.mkdir() Method

In this example Python script uses `os.mkdir()` to create a directory named “GeeksForGeeks” in the “/home/User/Documents” path. If the directory already exists, a `FileExistsError` will be raised. If the specified path is invalid, a `FileNotFoundError` will be raised.

Python3

import os

directory = "GeeksForGeeks"

parent_dir = "/home/User/Documents"

path = os.path.join(parent_dir, directory)

os.mkdir(path)

print ( "Directory '%s' created" % directory)

Output

Traceback (most recent call last): File "osmkdir.py", line 17, in os.mkdir(path) FileExistsError: [Errno 17] File exists: '/home/User/Documents/GeeksForGeeks'

Handling Error while using os.mkdir() Method

In this example Python script attempts to create a directory named “GeeksForGeeks” in the “/home/User/Documents” path using `os.mkdir(). If the directory already exists, an `OSError` is caught, and the error message is printed.

Python3

import os

path = '/home/User/Documents/GeeksForGeeks'

try :

`` os.mkdir(path)

except OSError as error:

`` print (error)

Output

[Errno 17] File exists: '/home/User/Documents/GeeksForGeeks'