What is the os.scandir() method in Python?

Overview

The os.scandir() method extracts an iterator of os.DirEntryObject containing directory info objects. These objects correspond to entries in a directory given by path. The entries in a directory are yielded in an arbitrarRandomlyy order and special entries like '.' 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 module
import os
# scan root directory
path = './'
# scan root directory to get os.DieEntry type iterator
scan= os.scandir(path)
# Now iterate through os.DirEnry and show files or directories
print("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 path variable, which holds a path that is going to be scanned.
  • Line 6: We invoke os.scandir(path) to get an iterator of the os.DirEntry type.
  • Line 8-11: We iterate through the os.DirEntry object and print the files in the current directory.