The Readlink() Function Of Os Module In Python

Overview:

  • The function readlink() retrieves the path of the actual file pointed to by a symbolic link. The path of the actual file is returned as a string.

Hard links and Soft links:

  • Both soft links and hard links refer to a file system entry. The commonality stops there.
  • A soft link is broken if the target it refers to is deleted. A hard link on the other hand is not just a link. It is another name for the target. Hence, as the number of hard links increases the link count to the target maintained by the operating system increases. The hard links can only refer to files and require those files to be present in the same file system. Hard links also occupy some minimal space without warranting any inode allocation. A hard link can be created using the function link().
  • Soft links are separate files which warrant an inode entry for themselves and they contain information on what they point to. Once a soft link is cut, the target is still alive. However, if the target is deleted, the soft link is not updated of this information and it becomes obsolete and broken. Soft links can point to both directories and files, while hard links point to only files. The entries pointed to by the soft links span multiple file systems. Soft links are popularly known as symbolic links and can be created using the function symlink().

Example:

# Example Python program that prints the
# file path pointed to by a symbolic link
import os

# Path of the symbolic link
symLinkPath = "/PythonProgs/TestFile"

# Read the actual file pointed to by the symbolic link
ptrTo         = os.readlink("/PythonProgs/TestFile")

print("The symbolic link is pointing to:")
print(ptrTo)

Output:

The symbolic link is pointing to:
/PythonProgs/l1/l2/l3/test.txt

 


Copyright 2023 © pythontic.com