Python os.path.lexists() Method

Python os.path.lexists() Method

  1. Syntax of Python os.path.lexists()
  2. Example Codes: Use of 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'
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.

Vaibhav Vaibhav avatar Vaibhav Vaibhav avatar

Vaibhav is an artificial intelligence and cloud computing stan. He likes to build end-to-end full-stack web and mobile applications. Besides computer science and technology, he loves playing cricket and badminton, going on bike rides, and doodling.

LinkedIn GitHub

Related Article - Python OS

  • Python os.set_handle_inheritable() Method
  • Python os.set_inheritable() Method
  • Python os.stat_result Class
  • Python os.renames() Method
  • Python os.get_handle_inheritable Method
  • Python os.get_inheritable Method