What is os.DirEntry.is_dir() in Python?

Overview

The OS module provides many functions to utilize the proper functionality of the operating system. os.scandir() is a method in the OS module that supports the os.DirEntry object.

This os.scandir() method helps to yield the os.DirEntry objects to the corresponding entries in a directory from the associated path. The os.DirEntry() method helps to check if the data entry is a directory or not.

Syntax


os.DirEntry.is_dir(* , follow_the_symlinks = True)

Parameters

It takes the following argument values.

  • *: These are the additional arguments. This is an optional parameter.
  • follow_the_symlinks: The default value for this parameter will be true. If the entry is a link, then follow_the_symlinks will set to true, otherwise it will set to false.

Return value

If the entry is a directory, it returns true. Otherwise, it is false.

Explanation

# Import OS module
import os
# Path to scan for directories
path = "./" # root path
# Using os.scandir() method
# to scan the folder for directories
with os.scandir(path) as iterate:
# For loop to check the directories
for entry in iterate :
#If entry is directory
if entry.is_dir() :
print("(%s) is a directory." % entry.name)
#Else if not directory
else:
print("(%s) is not a directory." % entry.name)
  • Line 2: We import the OS module in the program.
  • Line 5: We have a root path given in path variable.
  • Line 8: We use a method to give access to the path.
  • Line 9: We start a loop that iterates to check for directories.
  • Line 11: The if statement checks for directories and if it results in true, then prints the name of the directory.
  • Line 15: We use the else statement to print the name of the file, which does not turn out to be a directory.