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 betrue. If the entry is a link, thenfollow_the_symlinkswill set totrue, otherwise it will set tofalse.
Return value
If the entry is a directory, it returns true. Otherwise, it is false.
Explanation
# Import OS moduleimport os# Path to scan for directoriespath = "./" # root path# Using os.scandir() method# to scan the folder for directorieswith os.scandir(path) as iterate:# For loop to check the directoriesfor entry in iterate :#If entry is directoryif entry.is_dir() :print("(%s) is a directory." % entry.name)#Else if not directoryelse: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
pathvariable. - 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
ifstatement checks for directories and if it results intrue, then prints the name of the directory. - Line 15: We use the
elsestatement to print the name of the file, which does not turn out to be a directory.