The os.scandir()
method extracts an iterator of path
. The entries in a directory are yielded in an '.'
and '..'
are not included.
os.scandir(path='.')
It takes the following argument value:
path
: This is a path-like object representing the file system path. The default value is the current working directory. It returns an iterator of the os.DirEntry
type objects.
In the code snippet below, we check files in the root directory. To do this, we invoke os.scandir()
which returns an iterator of os.DirEntry
:
# importing os moduleimport os# scan root directorypath = './'# scan root directory to get os.DieEntry type iteratorscan= os.scandir(path)# Now iterate through os.DirEnry and show files or directoriesprint("Files/Directories at '% s':" % path)for entry in scan:print(entry.name)scan.close()
path
variable, which holds a path that is going to be scanned.os.scandir(path)
to get an iterator of the os.DirEntry
type.os.DirEntry
object and print the files in the current directory.