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 of os module yields os.DirEntry
objects corresponding to the entries in the directory given by specified path. os.DirEntry
object has various attributes and method which is used to expose the file path and other file attributes of the directory entry.
name
attribute on os.DirEntry
object is used to get the entry’s base filename, relative to the path argument used in os.scandir()
method.
Note: os.DirEntry
objects are intended to be used and thrown away after iteration as attributes and methods of the object cache their values and never refetch the values again. If the metadata of the file has been changed or if a long time has elapsed since calling os.scandir() method. we will not get up-to-date information.
Syntax: os.DirEntry.name
Parameter: None
Return value: This attribute returns an string value which represents the entry’s base filename.
Code #1: Use of os.DirEntry.name
attribute
# Python program to explain os.DirEntry.name attribute # importing os module import os # Directory to be scanned # Current working directory path = os.getcwd() # Using os.scandir() method # scan the specified directory # and yield os.DirEntry object # for each file and sub-directory print ( "Base filename of all directory entry in '% s':" % path) with os.scandir(path) as itr: for entry in itr : # Exclude the entry name # starting with '.' if not entry.name.startswith( '.' ) : # print entry's name print (entry.name) |
Base filename of all directory entry in '/home/ihritik': Public Desktop R foo.txt graph.cpp tree.cpp Pictures abc.py file.txt Videos images Downloads Lazyroar Music Documents
Code #2: Use of os.DirEntry.name()
attribute
# Python program to explain os.DirEntry.name attribute # importing os module import os # Directory to be scanned # Current working directory path = os.getcwd() # Using os.scandir() method # scan the specified directory # and yield os.DirEntry object # for each file and sub-directory print ( "All files and directory whose name starts with letter 'D' in '% s'" % path) with os.scandir(path) as itr: for entry in itr : # Check if directory entry name # starts with letter 'D' if entry.name.startswith( 'D' ) : # print entry's name print (entry.name) |
All files and directory whose name starts with letter 'D' in '/home/ihritik': Desktop Documents Downloads
References: https://docs.python.org/3/library/os.html#os.DirEntry.name