How to get symlink target in Python? How to get symlink target in Python? python python

How to get symlink target in Python?


The problem with os.readlink() is it will only resolve 1 step of the link. We can have a situation where A links to another link B, and B link is dangling.

$ ln -s /tmp/example/notexist /tmp/example/B$ ln -s /tmp/example/B /tmp/example/A$ ls -l /tmp/exampleA -> /tmp/example/BB -> /tmp/example/notexist

Now in Python, os.readlink gives you the first target.

>>> import os>>> os.readlink('A')'/tmp/example/B'

But in most situations I assume we are interested in the resolved path. So pathlib can help here:

>>> from pathlib import Path>>> Path('A').resolve()PosixPath('/tmp/example/notexist')

For older Python versions:

>>> os.path.realpath('A')'/tmp/example/notexist'


In Python 3.9 or above, pathlib.Path.readlink() can be used.

>>> p = Path('mylink')>>> p.symlink_to('setup.py')>>> p.readlink()PosixPath('setup.py')