Skip to content

Python os mkdir if not exists

  • by

In Python, you can use the os module to create a directory if it doesn’t already exist. Here’s an example of how you can achieve this:

import os

directory = "path/to/directory"

if not os.path.exists(directory):
    os.makedirs(directory)
    print(f"Directory '{directory}' created.")
else:
    print(f"Directory '{directory}' already exists.")

Output:

Python os mkdir if not exists

Make sure to replace "path/to/directory" with the actual path you want to create.

There is a simpler and more direct way to create a directory if it doesn’t already exist using the os.makedirs() function.

import os

directory = "path/to/directory"

os.makedirs(directory, exist_ok=True)

In this code, the os.makedirs() function is called with the exist_ok=True argument. This argument ensures that the function does not raise an exception if the directory already exists. If the directory doesn’t exist, it will be created.

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

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading