Python | os.DirEntry.is_file () method

File handling | Python Methods and Functions

os.scandir() of the os module os.DirEntry the os.DirEntry objects corresponding to the entries in the directory specified by the specified path. The os.DirEntry object has various attributes and a method that is used to provide the file path and other attributes of the directory entry file.

is_file() of the object os.DirEntry is used to check if the entry is a file or not.

Note: os.DirEntry are meant to be used and thrown away after iteration, as the object's attributes and methods cache their values ​​and never over-execute the values ​​again. If the file metadata has changed, or if a long time has passed since the os.scandir () method was called. we will not receive up-to-date information.

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

Parameter:
follow_symlinks: A boolean value is required for this parameter. If the entry is a symbolic link and follow_symlinks is True then the method will operate on the path symbolic link point to. If the entry is a symbolic link and follow_symlinks is False then the method will operate on the symbolic link itself. If the entry is not a symbolic link then follow_symlinks parameter is ignored. The default value of this parameter is True.

Return value: This method returns True if the entry is a file otherwise returns False.

Code # 1: Using the os.DirEntry.is_file()

# Python program to explain the os.DirEntry.is_file () method

 
# import of the os module

import os

 
# Directory to scan
# Path

path = "/ home / ihritik"

 
# Use Using the os.scandir () method
# check the specified directory
# and display the os.DirEntry object
# for each file and subdirectory

 

print ( "List of all files in path'% s': " % path) 

with os.scandir (path) as itr:

for entry in itr:

# Check if the post

# this file

if entry.is_file ():

# Print file name

print (entry.name)

Exit:

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

Code # 2: Using method os .DirEntry.is_file ()

# Python program to explain the os.DirEntry.is_file () method

 
# import of the os module

import os

 
# Directory for scanning
# Path

path = "/ home / ihritik"

 

 
# Print all filenames
# starting with & # 39; g & # 39;
# in the above path

  
# Using the os.scandir () method
# check the specified directory
# and output the os.DirEntry object
# for each file and subdirectory

 
with os.scandir (path) as itr:

for entry in itr:

# Check if the entry

# this is a file

if entry.is_file ():

if entry.name.startswith ( 'g' ):

  # Print file name

print (entry.name)

Output:

 graph.cpp 

Links: https://docs.p ython.org/3/library/os.html#os.DirEntry.is_file