What is the os.scandir() method in Python?
Overview
The os.scandir() method extracts an iterator of path. The entries in a directory are yielded in an '.' and '..' are not included.
Syntax
os.scandir(path='.')
Parameters
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.
Return value
It returns an iterator of the os.DirEntry type objects.
Explanation
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()
Line 2: We import the os module in this program.
Line 4: We create a
pathvariable, which holds a path that is going to be scanned.Line 6: We invoke
os.scandir(path)to get an iterator of theos.DirEntrytype.Line 8-11: We iterate through the
os.DirEntryobject and print the files in the current directory.