Python | os.scandir() method

OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality.

os.scandir() method in Python is used to get an iterator of os.DirEntry objects corresponding to the entries in the directory given by specified path.
The entries are yielded in arbitrary order and special entries ‘.’ and ‘..’ are not included.

Syntax: os.scandir(path = ‘.’)



Parameter:
path: A path-like object representing the file system path. This specify the directory to be scanned. If path is not specified then current working directory is used as path.
A path-like object is a string or bytes object which represents a path.

Return Type: This method returns an iterator of os.DirEntry objects corresponding to the entries in the given directory.

Code: Use of os.scandir() method

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to explain os.scandir() method 
  
# importing os module 
import os
  
  
# Directory to be scanned
path = '/home / ihritik'
  
# Scan the directiory and get
# an iterator of os.DirEntry objets
# corresponding to entries in it 
# using os.scandir() method
obj = os.scandir()
  
# List all files and diretories 
# in the specified path
print("Files and Directories in '% s':" % path)
for entry in obj :
    if entry.is_dir() or entry.is_file():
        print(entry.name)
  
  
# entry.is_file() will check
# if entry is a file or not and
# entry.is_dir() method will
# check if entry is a
# directory or not. 
  
  
# To Close the iterator and
# free acquired resources
# use scandir.close() method
obj.close()
  
# scandir.close() method is called automatically
# when the iterator is exhausted
# or garbage collected, or 
# when an error happens during iterating.

chevron_right


Output:

Files and Directories in '/home':
GeeksforGeeks
Videos
Downloads
Pictures
Documents
sample.txt
Public
Desktop
Images
R

Reference: https://docs.python.org/3/library/os.html#os.scandir



My Personal Notes arrow_drop_up

self motivated and passionate programmer

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.