知道兩個文件的絕對目錄,怎樣計算出兩個文件的相對目錄,例如:知道
a = '/usr/share/pyshared/test/a.py'
b = '/usr/lib/dist/test/a.py'
能夠直接應用OS模塊中的os.path.reppath獲得結果:
>>> print(os.path.relpath(a,b))
..\..\..\..\share\pyshared\test\a.py
python
可是計算結果是怎樣實現的呢?spa
def _abspath_split(path): abs = abspath(normpath(path)) prefix, rest = splitunc(abs) is_unc = bool(prefix) if not is_unc: prefix, rest = splitdrive(abs) return is_unc, prefix, [x for x in rest.split(sep) if x] def relpath(path, start=curdir): """Return a relative version of a path""" if not path: raise ValueError("no path specified") start_is_unc, start_prefix, start_list = _abspath_split(start) path_is_unc, path_prefix, path_list = _abspath_split(path) if path_is_unc ^ start_is_unc: raise ValueError("Cannot mix UNC and non-UNC paths (%s and %s)" % (path, start)) if path_prefix.lower() != start_prefix.lower(): if path_is_unc: raise ValueError("path is on UNC root %s, start on UNC root %s" % (path_prefix, start_prefix)) else: raise ValueError("path is on drive %s, start on drive %s" % (path_prefix, start_prefix)) # Work out how much of the filepath is shared by start and path. i = 0 for e1, e2 in zip(start_list, path_list): if e1.lower() != e2.lower(): break i += 1 rel_list = [pardir] * (len(start_list)-i) + path_list[i:] if not rel_list: return curdir return join(*rel_list)
上述代碼是relpath在Python中的內部實現,實現比較複雜,做爲簡單的可替代形式:rest
def ownrelpath(a,b): relpath = ''; la = a.split('/'); lb = b.split('/'); L = len(lb)-1; tt = ''; for i in range(len(la)-1): if la[i] == lb[i] and tt =='': continue; else: tt = tt+la[i]+"\\"; relpath = "..\\"*(L-1); print(relpath+tt);