Python 3 – os.readlink() Method
In Python, the os
module provides a variety of methods to work with the operating system like reading and writing files and directories, and it also provides a method to read the symbolic link. The os.readlink()
method is used to get the path to which the symbolic link points to.
The syntax of the os.readlink()
method is:
os.readlink(path)
Where, path
is the path of the symbolic link which we want to read.
Example
# importing os module
import os
# path of the directory where the symbolic link is located
path = "/home/desktop/symlink"
# printing the path to which the symbolic link points to
print(os.readlink(path))
In this example, we have used the os.readlink()
method to get the path to which the symbolic link points to.
Working of os.readlink()
method
In order to get a better understanding of the os.readlink()
method, let’s create a symbolic link and try to read it using the os.readlink()
method.
Creating a symbolic link
First, let’s create a symbolic link using the os.symlink()
method which is provided by the os
module.
# importing os module
import os
# path of the original file
original_path = "/home/desktop/original.txt"
# path of the symbolic link that we want to create
symlink_path = "/home/desktop/symlink"
# creating a symbolic link using os.symlink() method
os.symlink(original_path, symlink_path)
In this example, we created a symbolic link using the os.symlink()
method. We passed the path of the original file and the path of the symbolic link that we want to create.
Reading the symbolic link
# importing os module
import os
# path of the directory where the symbolic link is located
path = "/home/desktop/symlink"
# printing the path to which the symbolic link points to
print(os.readlink(path))
In this example, we used the os.readlink()
method to read the symbolic link. We passed the path of the symbolic link to the os.readlink()
method and it returns the path to which the symbolic link points.
Output:
/home/desktop/original.txt
Conclusion
In this article, we learned about the os.readlink()
method and how it works. We also saw some examples of how to use the os.readlink()
method to read the symbolic link. The os.readlink()
method is very useful when we want to follow the symbolic links and get the path of the final destination.