Python os.path.isdir() Method



The Python os.path.isdir() method is used to check whether a given path exists and points to a directory in the file system.

The method returns "True" if the specified path exists and refers to a directory in the file system, and "False" otherwise.

If the specified path does not exist or if it exists but is not a directory (e.g., it's a regular file, symbolic link, etc.), the method returns False.

Syntax

Following is the basic syntax of the Python os.path.isdir() method −

os.path.isdir(path)

Parameter

This method accepts a string as a parameter representing the path you want to check.

Return Value

The method returns a boolean value "True" or "False". It returns True if the specified path exists and is a directory, otherwise it returns False.

Example

In the following example, we are checking whether the path "dir_Path" corresponds to an existing directory using the isdir() method −

import os
dir_path = "/home/lenovo/Documents/file.txt" 
is_dir = os.path.isdir(dir_path)
print("The result obtained is:",is_dir)  

Output

The output obtained is as follows −

The result obtained is: True

Example

Here, we are checking whether the current working directory corresponds to an existing directory −

import os
current_dir = os.getcwd()
is_dir = os.path.isdir(current_dir)
print("The result obtained is:",is_dir)  

Output

Following is the output of the above code −

The result obtained is: True

Example

This example checks whether the path "/home/lenovo/symlink" corresponds to an existing directory, even if it is a symbolic link −

import os
link_path = "/home/lenovo/symlink"
is_dir = os.path.isdir(link_path)
print("The result obtained is:",is_dir)   

Output

We get the output as shown below −

The result obtained is: True

Example

Now, we are checking if the non-existent file path "/non/existent/path" corresponds to an existing directory or not −

import os
path = "/non/existent/path"
is_dir = os.path.isdir(path)
print("The result obtained is:",is_dir)   

Output

The result produced is as shown below −

The result obtained is: False
os_path_methods.htm
Advertisements