Open In App

os.DirEntry.is_dir() method-Python

Last Updated : 11 Jul, 2025
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

os.DirEntry.is_dir() method is used to determine whether a given entry retrieved using os.scandir()) is a directory. It returns True if the entry is a directory and False otherwise. This method is more efficient than manually checking with os.path.isdir() because it can use cached information from the operating system, reducing the number of system calls. We use the following folder structure in the example below:

Folder_structure
Folder structure

Example:

Python
import os

with os.scandir('.') as d:
    for e in d:
        if e.is_dir():
            print(e.name)

Output

example_folder

Explanation: This code lists directories only in the current folder (.). It doesn’t show subdirectories because os.scandir() scans one level at a time; to include subdirectories, use recursion.

Syntax of os.DirEntry.is_dir()

DirEntry.is_dir(*, follow_symlinks=True)

Parameters: follow_symlinks (optional) defaults to True. If set to False, symbolic links pointing to directories are not followed.

Returns: It returns True if the entry is a directory, False otherwise.

Why Use is_dir() Instead of os.path.isdir()?

Let’s dive deeper into why we prefer is_dir() over os.path.isdir() based on its key features. Understanding these benefits helps write faster and cleaner directory-handling code.

  • Performance Boost: is_dir() avoids extra system calls because os.scandir() fetches file attributes along with directory listing.
  • Cleaner Code: It reads more naturally when iterating directory contents.
  • Cached Metadata: Uses the metadata already collected during the scan.

Examples

Example 1: In this example, we are printing directories and their subdirectories by recursively scanning through them using the fun() function.

Python
import os

def fun(path):
    with os.scandir(path) as entries:
        for e in entries:
            if e.is_dir(follow_symlinks=False):
                print(e.path)
                fun(e.path)

fun('.')

Output

.\example_folder
.\example_folder\subdir1
.\example_folder\subdir2

Explanation: fun() function looks inside a folder and checks each item to see if it is a directory (ignoring shortcuts). If it is, the function prints the folder’s path and then looks inside that folder too, repeating this process to find all folders inside folders.

Example 2: In this example, we use the os module to scan the current directory and print the names of all entries that are directories, including symbolic links that point to directories.

Python
import os

with os.scandir('.') as d:
    for e in d:
        if e.is_dir(follow_symlinks=True):
            print(e.name)

Output

example_folder

Explanation: os.scandir('.') scans the current directory and returns all entries. for e in d loops through each entry and e.is_dir(follow_symlinks=True) checks if it's a directory, including symlinks to directories.

Exception handling

When working with directories, some paths may be inaccessible due to missing folders or restricted permissions. To ensure your program doesn't crash, it's important to handle potential exceptions like PermissionError or FileNotFoundError using a try-except block for safe and reliable directory traversal.

Python
import os

try:
    with os.scandir('/some/protected/path') as d:
        for e in d:
            if e.is_dir():
                print(e.name)
except PermissionError:
    print("Denied!")
except FileNotFoundError:
    print("Not found!")

Output

Not found!

Explanation: This code scans a directory to print its subdirectories using os.scandir(), handling errors safely with a try-except block. It catches PermissionError to print "Denied!" if access is blocked and FileNotFoundError to print "Not found!" if the directory doesn't exist.


Article Tags :
Practice Tags :

Similar Reads