Python os.path.islink() Method



The Python os.path.islink() method is used to check whether a given path exists and points to a symbolic link in the file system.

The method returns "True" if the specified path exists and is a symbolic link, and "False" otherwise.

If the specified path does not exist or if it exists but is not a symbolic link (e.g., it is a regular file, directory, etc.), the method returns False.

Syntax

Following is the basic syntax of the Python os.path.islink() method −

os.path.islink(path)

Parameter

This method accepts a string as a parameter representing the path you want to check.

Return Value

The method returns a boolean value "True" or "False". It returns True if the specified path exists and is a symbolic link, otherwise it returns False.

Example

In the following example, we are checking whether the path "link_Path" corresponds to a symbolic link using the islink() method −

import os
link_path = "/home/lenovo/symlink"
is_link = os.path.islink(link_path)
print("The result obtained is:",is_link)  

Output

The output obtained is as follows −

The result obtained is: True

Example

Here, we are checking whether the current working directory corresponds to a symbolic link −

import os
current_dir = os.getcwd()
is_link = os.path.islink(current_dir)
print("The result obtained is:",is_link)  

Output

Following is the output of the above code −

The result obtained is: True

Example

This example checks whether the path "/home/lenovo/symlink" corresponds to a symbolic link, even if it is a directory −

import os
dir_path = "/home/lenovo/Documents"
is_link = os.path.islink(dir_path)
print("The result obtained is:",is_link)   

Output

We get the output as shown below −

The result obtained is: True

Example

Now, we are checking if the non-existent file path "/non/existent/path" corresponds to a symbolic link or not −

import os
path = "/nonexistent/file.txt"
is_link = os.path.isdir(path)
print("The result obtained is:",is_link)   

Output

The result produced is as shown below −

The result obtained is: False
os_path_methods.htm
Advertisements