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.
os.DirEntry.is_dir(* , follow_the_symlinks = True)
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
.If the entry is a directory, it returns true
. Otherwise, it is false
.
# 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)
path
variable.if
statement checks for directories and if it results in true
, then prints the name of the directory. else
statement to print the name of the file, which does not turn out to be a directory.