Python os.readlink() Method

Python os.readlink() method is used to resolve a symbolic link. It returns the path to which the symbolic link points and does not follow the link but only retrieves the link target.

Syntax

os.readlink(path, *, dir_fd=None)

Parameters

Name Description
path (string) The path of the symbolic link.
dir_fd (optional A file descriptor refers to a directory.

Return value

It returns a string representing the path to which the symbolic link points.

Example 1: Reading a symbolic link

Here is a symlink file which we will read:

Screenshot of a link file which we will read

import os

symlink_path = 'dir/symlink'

actual_path = os.readlink(symlink_path)

print(f"The symlink points to: {actual_path}")

Output

The symlink points to: dir/file.txt

The “symlink” file points to the “dir/file.txt” file.

Screenshot of symlink points to source file

Example 2: Handling FileNotFoundError

If the provided path is not a symbolic link, it will throw a FileNotFoundError.

You can use the try/except mechanism to handle the error.

import os

try:
  actual_path = os.readlink('nonexistent_symlink')
except FileNotFoundError as error:
  print(f"Error: {error}")

Output

Error: [Errno 2] No such file or directory: 'nonexistent_symlink'

This method is helpful in various scenarios, such as resolving symlinks to get the actual file path or verifying symlink targets.

Example 3: Handling OSError: [Errno 22] Invalid argument

import os

file_path = 'dir/file.txt'
# Attempt to use os.readlink() on a regular file
try:
  os.readlink(file_path)
except OSError as e:
  print(f"Caught an OSError: {e}")

Output

Caught an OSError: [Errno 22] Invalid argument: 'dir/file.txt'

Since the os.readlink() function is designed to read symbolic links, using it on a regular file will raise an OSError: Invalid argument error.

Leave a Comment

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