Open In App

Python | os.DirEntry.is_symlink() method

Improve
Improve
Like Article
Like
Save
Share
Report

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.

is_symlink() method on os.DirEntry object is used to check if an entry is a symbolic link.

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.is_symlink()

Parameter: None

Return value: This method returns True if the entry is a symbolic link (even if broken) otherwise returns False.

Code #1: Use of os.DirEntry.is_symlink() method




# Python program to explain os.DirEntry.is_symlink() method 
  
# importing os module  
import os
  
# Directory to be scanned
# Path
path = "/home / ihritik"
  
# Print all symbolic links
# in the above path
  
# Using os.scandir() method
# scan the specified directory
# and yield os.DirEntry object
# for each file and sub-directory
obj = os.scandir(path)
  
print("Symbolic links in the path '% s':" % path)
for entry in obj :
    # Check if the entry
    # is a symbolic link
    # using os.DirEntry.is_symlink() method
    if entry.is_symlink() :
        # Print symbolic link
        # full path    
        print(entry.path)
         


Output:

Symbolic links in the path '/home/ihritik':
/home/ihritik/file.txt
/home/ihritik/sample.py

Code: Use of os.DirEntry.is_symlink() method




# Python program to explain os.DirEntry.is_symlink() method 
  
# importing os module  
import os
  
# Directory to be scanned
# Path
path = "/home / ihritik"
  
# Count number of
# symbolic links
# in the above path
  
# Using os.scandir() method
# scan the specified directory
# and yield os.DirEntry object
# for each file and sub-directory
obj = os.scandir(path)
  
count = 0;
  
for entry in obj :
    # Check if the entry
    # is a symbolic link
    # using os.DirEntry.is_symlink() method
    if entry.is_symlink() :
        count = count + 1
          
  
print("Count of symbolic links in the path '% s':" % path, count)


Output:

Count of symbolic links in the path '/home/ihritik': 2

References: https://docs.python.org/3/library/os.html#os.DirEntry.is_symlink



Last Updated : 26 Aug, 2019
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads