Check If Directory Exist In Python

Python provides different methods and ways in order to check if a directory exists. Generally, the os.path module is used to check the specified directory if it exists. In this tutorial, we examine all Python methods to check directory existence.

Check If Directory Exists with os.path.exists() Method

Python provides os.path for different operating-related methods. The exist() method can be used to check if a specified directory exists. If a specified directory exists the True value is returned, if does not exist False is returned. The directory name or full path is provided as a parameter to the exist() method.

import os

os.path.exists("/home/ismail/")

Alternatively, we can provide only the directory name if it is located in the current working directory.

import os

os.path.exists("/data/")

Check If Directory Exists with os.path.isdir() Method

The native and most common way to check a directory’s existence is using the os.path.isdir() method. As expected the os module should be imported. The directory we want to check is provided to the isdir() mehtod as a parameter. If the directory exists the True value is returned and if it does not exist False is returned.

import os

os.path.isdir("/home/ismail/")

Alternatively, we can provide only the directory name if it is located in the current working directory.

import os

os.path.isdir("/data/")

Check If Directory Exists with pathlib.Path.exists() Method

Another popular module to work with directories is the pathlib module. We can use pathlib.Path.exists() method in order to check directory existence. the directory name or path is provided as a parameter to the exists() method.

import pathlib

pathlib.Path.exists("/home/ismail/")

Leave a Comment