Python os.DirEntry.is_file() – Check if entry is a file

Python os.DirEntry.is_file() Method

Python The os module’s os.scandir() method produces an os.DirEntry object corresponding to an entry in the directory given by the specified path. os.DirEntry objects have various attributes and methods that expose the file path and other file attributes of a directory entry.

The is_file() method on an os.DirEntry object is used to check if an entry is a file.

Note: os.DirEntry objects are intended to be used and discarded after iteration, as their attributes and methods cache their values and are never retrieved. If the file’s metadata has changed, or if a significant amount of time has passed since the os.scandir() method was called, we will no longer have the most up-to-date information.

os.DirEntry.is_file Syntax

os.DirEntry.is_file(*, follow_symlinks = True)

os.DirEntry.is_file Parameters

follow_symlinks: This parameter takes a Boolean value. If the entry is a symbolic link and follow_symlinks is True, the method will operate on the path pointed to by the symbolic link. If the entry is a symbolic link and follow_symlinks is False, the method will operate on the symbolic link itself. If the entry is not a symbolic link, the follow_symlinks parameter is ignored. The default value is “True”.

Return Value: If the entry is a file, this method returns True, otherwise it returns False.

os.DirEntry.is_file example 1

Use the os.DirEntry.is_file() method

# Python program to explain os.DirEntry.is_file() method
  
# importing os module
import os
  
# Directory to be scanned
#Path
path = "/home/ihritik"
  
# Using os.scandir() method
# scan the specified directory
# and yield os.DirEntry object
# for each file and sub-directory
  
print("List of all files in path '% s':" % path)
with os.scandir(path) as itr:
for entry in itr :
         # Check if the entry
         # is a file
           if entry.is_file():
                                                                            
print(entry.name)

Output:

List of all files in path '/home/ihritik':
file.txt
tree.cpp
graph.cpp
abc.txt

os.DirEntry.is_file example 2

Use the os.DirEntry.is_file() method

# Python program to explain os.DirEntry.is_file() method
  
# importing os module
import os
  
# Directory to be scanned
#Path
path = "/home/ihritik"
  
  
# Print all file names
# starting with letter 'g'
# in above specified path
  
# Using os.scandir() method
# scan the specified directory
# and yield os.DirEntry object
# for each file and sub-directory
  
with os.scandir(path) as itr:
for entry in itr :
         # Check if the entry
         # is a file
           if entry.is_file():
                  if entry.name.startswith('g'):
                                                                                           
print(entry.name)

Output:

graph.cpp

Leave a Reply

Your email address will not be published. Required fields are marked *