Skip to content

Instantly share code, notes, and snippets.

@jsonw23
Created February 13, 2015 15:32
Show Gist options
  • Select an option

  • Save jsonw23/a46d3019febb0a09985d to your computer and use it in GitHub Desktop.

Select an option

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
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