Suppose your application needs to know the relative path from one path to another (say because you want to create a symbolic link, a relative reference in a URL, etc). These functions may be of help.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | #!/usr/bin/env python
#
# Author: Cimarron Taylor
# Date: July 6, 2003
# File Name: relpath.py
# Program Description: Print relative path from /a/b/c/d to /a/b/c1/d1
#
# helper functions for relative paths
#
import os
def pathsplit(p, rest=[]):
(h,t) = os.path.split(p)
if len(h) < 1: return [t]+rest
if len(t) < 1: return [h]+rest
return pathsplit(h,[t]+rest)
def commonpath(l1, l2, common=[]):
if len(l1) < 1: return (common, l1, l2)
if len(l2) < 1: return (common, l1, l2)
if l1[0] != l2[0]: return (common, l1, l2)
return commonpath(l1[1:], l2[1:], common+[l1[0]])
def relpath(p1, p2):
(common,l1,l2) = commonpath(pathsplit(p1), pathsplit(p2))
p = []
if len(l1) > 0:
p = [ '../' * len(l1) ]
p = p + l2
return os.path.join( *p )
def test(p1,p2):
print "from", p1, "to", p2, " -> ", relpath(p1, p2)
if __name__ == '__main__':
test('/a/b/c/d', '/a/b/c1/d1')
|
Tags: files
abs2rel and rel2abs. ignore previous comment - characters didn't get escaped properly.
Better pathsplit.