Python os.path.lexists() Method



The Python os.path.lexists() method is used to check whether a specified path exists in the file system, considering symbolic links. It is similar to the exists() method, but it also follows symbolic links to determine if the final target of the link exists.

  • The method returns True if the specified path exists in the file system, or if there is a symbolic link that points to an existing file system object, and False otherwise.
  • If the path exists and is not a symbolic link, or if the path does not exist but there is a symbolic link that points to an existing object, the method returns True.
  • If the path does not exist or if there are permission issues preventing access to the path, and there is no symbolic link pointing to an existing object, the method returns False.

Syntax

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

os.path.lexists(path)

Parameter

This method accepts a string as a parameter representing the path that you want to check for existence, considering symbolic links.

Return Value

The method returns a boolean value "True" or "False". It returns True if the specified path exists in the file system, regardless of whether it's a symbolic link, otherwise it returns False.

Example

In the following example, we are checking whether the file path "/home/lenovo/documents/file.txt" exists in the filesystem, including symbolic links using the lexists() method −

import os
file_path = "/home/lenovo/documents/file.txt"
exists = os.path.lexists(file_path) 
print("The result is:",exists)      

Output

The output obtained is as follows −

The result is: True

Example

Here, we are checking whether the Windows file path "C:\Users\user\Documents\file.txt" exists in the filesystem, including symbolic links using the lexists() method −

import os
file_path = "C:\\Users\\Lenovo\\Documents\\file.txt"
exists = os.path.lexists(file_path)
print("The result is:",exists)   

Output

Following is the output of the above code −

The result is: True

Example

In this example, we are checking whether the given directory path "dir_path" exists in the filesystem, including symbolic links using the exists() method −

import os
dir_path = "/home/Lenovo/documents/directory/"
exists = os.path.lexists(dir_path)
print("The result is:",exists)      

Output

The result produced is as shown below −

The result is: True

Example

This example shows that if the given path is non-existent and there is no symbolic link pointing to an existing object, the lexists() method returns False −

import os
path = "/non/existent/path"
exists = os.path.lexists(path)
print("The result is:",exists)  

Output

We get the output as shown below −

The result is: False 
os_path_methods.htm
Advertisements