python

Check if a directory exists using Python

You can use the os module of Python to check whether a directory exists or not. You can check more methods in this post for the same.

import os

# Check using os.path.isdir
os.path.isdir("DIRECTORY_PATH")

# Check using os.path.exists
os.path.exists("DIRECTORY_PATH")

We are using the os module of Python here to check if a directory exists on the system or not. In the above code snippet:

  1. We have imported the Python os module.
  2. We have used os.path.isdir() and passed the directory path to it as a parameter. It will return true if the directory exists and false if not exists.
  3. We can also use os.path.exists() and pass directory path to it. It will also return true if a directory exists on the system.

You can make a directory path as below

directory_path = os.path.join(os.getcwd(), 'folder_name')
from pathlib import Path

# Check for a folder
Path('folder_name').is_dir()

# Check for a file
(Path.cwd() / 'folder_name' / 'file_name.txt').exists()
We are using the path() function of pathlib module to check whether a directory exists or not using Python.
import os

dir_path = '/usr/bin/folder_name'

os.path.is_dir(dir_path)
We are using is_dir() method of the os module to check if a directory exists or not. We have defined the directory path variable here. and passed it to the method os.path.is_dir(). It will return true if the directory exists.
import os

directory_path = '/usr/folder_name'

os.path.exists(directory_path)
We are using os.path.exists() here to check whether a folder or directory exists or not. We have created a variable that contains the path of the directory and passed it to the exists() function. It will return True if the directory exists.
Was this helpful?