Python os.path.lexists() Method

Python os.path.lexists() method is used to check whether a path of symbolic links exists.

Unlike os.path.exists(), os.path.lexists() will return True even if the path is a symbolic link that points to a non-existent file.

Syntax

os.path.lexists(path)

Parameters

Name Description
path (string, required) It is a symbolic file path you want to check

Return value

It returns True if the path exists or if it’s a symbolic link (even if the link is broken). Otherwise, it returns False.

Visual Representation

Understanding of how Python os.path.lexist() Method works

Example 1: Checking path and symbolic links

We will check the path of the “symlink” symbolic file that exists in our current working directory:

Screenshot of File path of symlink

import os

# Given a path, which can be a regular file, directory, or a symbolic link
path = 'symlink'

# Check if the path or symbolic link exists
if os.path.lexists(path):
  print(f"The path or symbolic link '{path}' exists.")
else:
  print(f"The path or symbolic link '{path}' does not exist.")

Output

The path or symbolic link 'symlink' exists.

Example 2: Checking for non-existent symlink

import os

# Given a path, which can be a regular file, directory, or a symbolic link
path = 'non_existent_link'

# Check if the path or symbolic link exists
if os.path.lexists(path):
  print(f"The path or symbolic link '{path}' exists.")
else:
  print(f"The path or symbolic link '{path}' does not exist.")

Output

The path or symbolic link 'non_existent_link' does not exist.

That’s all!

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.