Python os.path.lexists() Method
The lexists() method belongs to the os.path module, a set of utilities to work with file system paths. The lexists() method verifies if a path exists or not.
Syntax of Python os.path.lexists()
os.path.lexists(path)
Parameters
path |
A file system path. |
Returns
The lexists() method returns a Boolean value. If the path is valid or a symbolic link, even if it is broken, it returns True.
On the contrary, it returns False for every invalid path.
Example Codes: Use of Python os.path.lexists() Method
Before we proceed, create a file, data.txt, in the current working directory and add some random information to it. Also, create a soft link or symbolic link to it using the ln command.
Use the following command in case you are not familiar with it.
ln -s 'data.txt' 'data-symlink.txt'
Symbolic Link to a Resource
from os.path import lexists
path = "/home/user/documents/files/data-symlink.txt"
print(lexists(path))
Output:
True
Since this symbolic link exists and we have provided a genuine path, the lexists() method returns True.
Path to a Resource
from os.path import lexists
path = "/home/user/documents/files/data.txt"
print(lexists(path))
Output:
True
Since this file exists and we have provided a genuine path, the lexists() method returns True.
Invalid Path to a Resource
from os.path import lexists
path = "/home/user/documents/somthing.txt"
print(lexists(path))
Output:
False
Since somthing.txt doesn’t exist, the lexists() method returns False.
On some operating systems, this method is analogous to the exists() method, which also belongs to the os.path module.
