Search code examples
pythonpathos.pathpathlib

Python pathlib: Resolve full path to symbolic link without following it


Let's say I have a link/home/me/folder/link that points to /home/me/target. When I call

pathlib.Path("link").resolve()

from /home/me/folder/, it will return the resolved path to the target, not the resolved path of the link. How can I get the latter using pathlib (there don't seem to be any options for resolve())?

(with os.path the equivalent of what I'm looking for would beos.path.abspath("link"))


Solution

  • pathlib.Path has an absolute method that does what you want.

    $  mkdir folder
    $  touch target
    $  ln -s ~/target ~/folder/link
    $  ls -l folder/
    total 0
    lrwxrwxrwx 1 me users 16 Feb 20 19:47 link -> /home/me/target
    $  cd folder
    
    $/folder  python3.7 -c 'import os.path;print(os.path.abspath("link"))'
    /home/me/folder/link
    
    $/folder  python3.7 -c 'import pathlib;p = pathlib.Path("link");print(p.absolute())'
    /home/me/folder/link
    

    The method doesn't appear in the module documentation, but its docstring reads:

    Return an absolute version of this path. This function works even if the path doesn't point to anything. No normalization is done, i.e. all '.' and '..' will be kept along. Use resolve() to get the canonical path to a file.

    It's worth noting that there are comments in the method code (in the 3.7 branch) that suggest it may not be fully tested on all platforms.