Skip to content

Python os mkdir exist_ok

  • by

In Python, the os.mkdir function is used to create a new directory. The exist_ok parameter is a boolean flag that determines the behavior of os.mkdir when the directory already exists.

If exist_ok is set to False (the default), os.mkdir will raise a FileExistsError if the directory already exists. This means that an exception will be raised if you attempt to create a directory that is already present in the file system.

import os

directory = 'my_directory'

# Using os.makedirs with exist_ok=True
os.makedirs(directory, exist_ok=True)
print(f"Directory '{directory}' created if it didn't exist.")

If exist_ok is set to True, os.mkdir will not raise any exceptions if the directory already exists. It will silently continue execution without making any changes to the file system. This is useful when you want to create a directory only if it doesn’t exist, but don’t want to raise an exception if it’s already there.

Python os mkdir exist_ok example

Here’s an example that demonstrates the usage of os.mkdir with exist_ok:

import os

directory = 'my_directory'

try:
    os.makedirs(directory, exist_ok=True)
    print(f"Directory '{directory}' created if it didn't exist.")
except FileExistsError:
    print(f"Directory '{directory}' already exists.")

Output:

Python os mkdir exist_ok

In the above example, the os.makedirs() function is used with exist_ok=True. It will create the directory 'my_directory' if it doesn’t exist, and it will not raise an exception if the directory already exists. The FileExistsError exception is caught by the except block, which prints a message indicating that the directory already exists.

Note: if you only want to create a single directory (without creating parent directories if they don’t exist), you can use the os.mkdir() function without the exist_ok parameter, as shown in the previous response.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *