Created
February 13, 2015 15:32
-
-
Save jsonw23/a46d3019febb0a09985d to your computer and use it in GitHub Desktop.
Get the relative path from one full path to another full path using Python Path object
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| def make_rel_path(from_path, to_path): | |
| from_path = Path(from_path) | |
| to_path = Path(to_path) | |
| rel_url = to_path.name | |
| for parent2 in to_path.parents: | |
| up = 0 | |
| for parent1 in from_path.parents: | |
| up += 1 | |
| if parent1 == parent2: | |
| common = parent1 | |
| if common == from_path: | |
| return rel_url | |
| else: | |
| return ("../" * (up - 1)) + rel_url | |
| rel_url = parent2.name + '/' + rel_url |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment