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.
The os.scandir() method in Python is used to get an iterator of os.DirEntry objects corresponding to the entries in the directory given by the 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
Python3
import os
path = '/home/ihritik'
obj = os.scandir(path)
print ( "Files and Directories in '% s':" % path)
for entry in obj :
if entry.is_dir() or entry.is_file():
print (entry.name)
obj.close()
|
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
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
08 Aug, 2021
Like Article
Save Article