How to get the relative path between two absolute paths in Python using pathlib?

rug*_*tal 5 python python-3.x pathlib

In Python 3, I defined two paths using pathlib, say:

from pathlib import Path

origin = Path('middle-earth/gondor/minas-tirith/castle').resolve()
destination = Path('middle-earth/gondor/osgiliath/tower').resolve()
Run Code Online (Sandbox Code Playgroud)

How can I get the relative path that leads from origin to destination? In this example, I'd like a function that returns ../../osgiliath/tower or something equivalent.

Ideally, I'd have a function relative_path that always satisfies

origin.joinpath(
    relative_path(origin, destination)
).resolve() == destination.resolve()
Run Code Online (Sandbox Code Playgroud)

(well, ideally there would be an operator - such that destination == origin / (destination - origin) would always be true)

Note that Path.relative_to is not sufficient in this case, since origin is not a destination's parent. Also, I'm not working with symlinks, so it's safe to assume that there are none if this simplifies the problem.

How can relative_path be implemented?

Ada*_*ith 6

This is trivially os.path.relpath

import os.path
from pathlib import Path

origin      = Path('middle-earth/gondor/minas-tirith/castle').resolve()
destination = Path('middle-earth/gondor/osgiliath/tower').resolve()

assert os.path.relpath(destination, start=origin) == '..\\..\\osgiliath\\tower'
Run Code Online (Sandbox Code Playgroud)

  • 这太棒了,谢谢!我认为 `pathlib` 会有如此看似简单的功能,不认为我必须去其他地方寻找。您知道是否有办法仅使用“pathlib”来做到这一点?不管怎样,你的解决方案效果很好。 (3认同)