知道两个文件的绝对目录,怎样计算出两个文件的相对目录,例如:知道
a = '/usr/share/pyshared/test/a.py'
b = '/usr/lib/dist/test/a.py'
可以直接应用OS模块中的os.path.reppath得到结果:
>>> print(os.path.relpath(a,b))
........sharepyshared esta.py
但是计算结果是怎样实现的呢?
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中的内部实现,实现比较复杂,作为简单的可替代形式:
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);