Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

scandir
os module
python programming
communitycreator

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

Salman Yousaf

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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.

RELATED TAGS

scandir
os module
python programming
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring