Issue
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()
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()
Note that Path.relative_to
is insufficient in this case since origin
is not a destination
's parent. Also, I'm not working with symlinks, so it's safe to assume there are none if this simplifies the problem.
How can relative_path
be implemented?
Solution
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'
Answered By - Adam Smith
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.