Open In App

os.path.isdir() method – Python

Last Updated : 28 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

os.path.isdir() method in Python checks whether the specified path is a directory or not. This method follows the symbolic link, which means if the specified path is a symbolic link pointing to an existing directory then the method will return True.

Example: Using os.path.isdir() method

This code demonstrates how to check whether a given path refers to a directory using the os.path.isdir() function in Python. It checks two paths: one for a file and another for a directory.

Python
import os.path

path = '/home/User/Documents/file.txt'
isdir = os.path.isdir(path)
print(isdir)

path = '/home/User/Documents/'
isdir = os.path.isdir(path)
print(isdir)

Output
False
True

Explanation: This code checks whether the specified paths refer to directories using the os.path.isdir() function. The first check (/home/User/Documents/file.txt) is for a file, so it returns False because the path is not a directory. The second check (/home/User/Documents/) is for a directory, so it returns True because the path points to an existing directory.

Syntax

os.path.isdir(path) 

  • Parameter: A path-like object representing a file system path. 
  • Return Type: This method returns a Boolean value of class bool. This method returns True if the specified path is an existing directory, otherwise returns False.

Note: isdir() stands for “is directory”, which justifies its task for checking if the given path is a directory.

This code demonstrates how to create a directory and a symbolic link in Python, and then checks whether those paths refer to directories using the os.path.isdir() function.

Python
import os.path

os.mkdir("GeeksForGeeks")
os.symlink("GeeksForGeeks", "/home/User/Desktop/gfg")
print(os.path.isdir("GeeksForGeeks"))
print(os.path.isdir("/home/User/Desktop/gfg"))

Output
True
True

Explanation: This code creates a directory “GeeksForGeeks” using os.mkdir() and a symbolic link pointing to it using os.symlink(). It then checks if both the directory and the symbolic link are valid directories using os.path.isdir(). The first check returns True for the “GeeksForGeeks” directory, and the second check returns True for the symbolic link, as it points to an existing directory.


Next Article
Practice Tags :

Similar Reads