The Python method readlink() of OS module takes the path of a symbolic link as its argument and returns the path to which the symbolic link points. It may return an absolute or relative pathname.
SyntaxFollowing is the syntax for Python os.readlink() method −
os.readlink(path, *, dir_fd)Parameters
The parameter of Python os.readlink() method is as follows −
path − It specifies the path or symblic link for which we are going to find source of the link.
dir_fd − This is an optional argument that's a file descriptor referring to a directory.
The Python os.readlink() method return a string representing the path to which the symbolic link points.
ExampleThe following example shows the usage of readlink() method. Here, we first create a symbolic link to a file and then display the original file path.
import os src = '/usr/bin/python' dst = '/tmp/python' # This creates a symbolic link on python in tmp directory os.symlink(src, dst) # Now let us use readlink to display the source of the link. path = os.readlink("Source link:", dst ) print path
Let us compile and run the above program, this will create a symblic link to /usr/bin/python and later it will read the source of the symbolic link using readlink() call. Before running this program make sure you do not have /tmp/python already available in your system.
Source link: /usr/bin/pythonExample
If the specified path is not a symbolic link, the os.readlink() will raise an OSError. The below example illustrates the same.
import os try: # reading a path that doesn't exist src = os.readlink("/tmp/path") print(f"Source Path: {result}") except OSError as exp: print(f"Error: {exp}")
On executing the above code, it will produce the following output −
Error: [Errno 2] No such file or directory: '/tmp/path'
python_files_io.htm
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4