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.
path
attribute of os.DirEntry
object is used to get entry’s full path name. The full path is absolute only if the path parameter used in os.scandir() method is absolute. Also if os.scandir() method path parameter was a file descriptor then the value of os.DirEntry.path
attribute is same as os.DirEntry.name
attribute.
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.path
Parameter: None
Return value: This attribute returns a bytes value if os.scandir() path parameter is bytes otherwise returns a string value which represents the entry’s full path.
Code #1: Use of os.DirEntry.path
attribute
# Python program to explain os.DirEntry.path 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 ( "Full path 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 # and its full path print (entry.name, ":" , entry.path) |
Full path of all directory entry in '/home/ihritik': Public : /home/ihritik/Public Desktop : /home/ihritik/Deskop R : /home/ihritik/R foo.txt : /home/ihritik/foo.txt graph.cpp : /home/ihritik/graph.cpp tree.cpp : /home/ihritik/tree.cpp Pictures : /home/ihritik/Pictures abc.py : /home/ihritik/abc.py file.txt : /home/ihritik/file.txt Videos : /home/ihritik/Videos images : /home/ihritik/images Downloads : /home/ihritik/Downloads Lazyroar : /home/ihritik/Lazyroar Music : /home/ihritik/Music Documents : /home/ihritik/Documents
References: https://docs.python.org/3/library/os.html#os.DirEntry.path