Python os.readlink() Method

Python os.readlink() Method

  1. Syntax of the os.readlink() Method
  2. Example Codes: Working With the os.readlink() Method in Python
  3. Example Codes: Find the Absolute Path Using the os.readlink() Method in Python
  4. Example Codes: Understanding the os.readlink() Method in Python

Python os.readlink() method is an efficient way of finding a path using a symbolic link. It may return an absolute or a relative path of the symbolic link to which it relates.

os.readlink(path address)
os.readlink(path address, *, fd_dir = None)

Parameters

path address It is an address object of a file system path or a symlink. The object can either be an str or bytes.
* The asterisk shows that all following parameters are keyword-only.
fd_dir It is an optional parameter representing a file descriptor referring to a path. Its default value is set as None.

Return

The return type of this method is a path string relating to the symlink entered as the parameter. A string object is returned if the symlink is also a string object, and a byte object is returned if the symlink is a byte object.

import os

path_address = "/home"

link = "/home/File.txt"

os.symlink(path_address, link)

Path = os.readlink(link)

print("The symbolic link points to", Path)

Output:

The symbolic link points to /home

An OSError might occur while using the os.readlink() method due to invalid or inaccessible processes and paths.

import os

path_address = "/home"

link = "/home/File.txt"

os.symlink(path_address, link)

Path = os.readlink(link)

print("The symbolic link points to the following absolute path: ", os.path.realpath(Path))

Output:

The symbolic link points to the following absolute path:  /home

When resolving a path containing links, you can use os.path.realpath() to properly handle recursion and systems and platform differences.

import os

path_address = '/tmp/' + os.path.basename(__file__)

print('Creating a new link {} -> {}'.format(path_address, __file__))

os.symlink(__file__, path_address)

print('The symlink points to:', os.readlink(path_address))

Output:

Creating a new link /tmp/main.py -> main.py
The symlink points to: main.py

Note that the file descriptors returned by the method os.readlink() are non-inheritable.

Musfirah Waseem avatar Musfirah Waseem avatar

Musfirah is a student of computer science from the best university in Pakistan. She has a knack for programming and everything related. She is a tech geek who loves to help people as much as possible.

LinkedIn

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