Python os.path.lexists() method explanation with example

Python os.path.lexists() explanation with example:

Python os.path.lexists is a method defined in the os.path submodule. os.path submodule is defined in os module. Since os is an inbuilt module in python, we can import it directly using an import statement without requiring to install any other third party library.

os.path.lexists() is used mainly to check if a path exists or not. We can pass one full path or relative path and it will return one boolean value based on the result it finds. It is similar to os.path.exists. The only difference is that it returns True for broken symbolic links.

In this post, we will learn how to use os.path.lexists with an example.

Definition of os.path.lexists:

os.path.lexists is defined as below:

os.path.lexists(path)

It takes the path as the parameter and returns one boolean value. For an existing path, it returns True. Else, it returns False.

The only difference between os.path.exists and os.path.lexists is that lexists returns True for broken symbolic links, but exists returns False for that.

Example of os.path.lexists:

Let’s take a look at the example below:

import os

print(os.path.lexists('/Users/cvc/Documents'))
print(os.path.lexists('/Users/cvc/Documents/file.png'))
print(os.path.lexists('./'))
print(os.path.lexists('../../../'))
print(os.path.lexists('.'))
print(os.path.lexists(''))

It will print the below output:

True
False
True
True
True
False

The second statement returned False because the file file.png doesn’t exists in the Documents folder. The last statement also returned False because the path given is invalid. Other than that, other statements are returning True because all are valid paths.

If you run the above program using exists, it will print the same output.

import os

print(os.path.exists('/Users/cvc/Documents'))
print(os.path.exists('/Users/cvc/Documents/file.png'))
print(os.path.exists('./'))
print(os.path.exists('../../../'))
print(os.path.exists('.'))
print(os.path.exists(''))

It will print similar result.

You might also like: