diff options
author | Collin Winter <collinw@gmail.com> | 2007-03-16 22:16:08 (GMT) |
---|---|---|
committer | Collin Winter <collinw@gmail.com> | 2007-03-16 22:16:08 (GMT) |
commit | 6f187743ffbce522c9d686ae5393272c1eb85dcc (patch) | |
tree | 49954823525566e80d435c3f9acff30a1a54e58d /Lib/ntpath.py | |
parent | 6de691d78ce696d897e4c58c3fc8fd7d3f6f1359 (diff) | |
download | cpython-6f187743ffbce522c9d686ae5393272c1eb85dcc.zip cpython-6f187743ffbce522c9d686ae5393272c1eb85dcc.tar.gz cpython-6f187743ffbce522c9d686ae5393272c1eb85dcc.tar.bz2 |
Patch 1339796: add a relpath() function to os.path.
Diffstat (limited to 'Lib/ntpath.py')
-rw-r--r-- | Lib/ntpath.py | 28 |
1 files changed, 27 insertions, 1 deletions
diff --git a/Lib/ntpath.py b/Lib/ntpath.py index 60c1fd0..99d7a4a 100644 --- a/Lib/ntpath.py +++ b/Lib/ntpath.py @@ -16,7 +16,7 @@ __all__ = ["normcase","isabs","join","splitdrive","split","splitext", "getatime","getctime", "islink","exists","lexists","isdir","isfile", "ismount","walk","expanduser","expandvars","normpath","abspath", "splitunc","curdir","pardir","sep","pathsep","defpath","altsep", - "extsep","devnull","realpath","supports_unicode_filenames"] + "extsep","devnull","realpath","supports_unicode_filenames","relpath"] # strings representing various path-related bits and pieces curdir = '.' @@ -465,3 +465,29 @@ realpath = abspath # Win9x family and earlier have no Unicode filename support. supports_unicode_filenames = (hasattr(sys, "getwindowsversion") and sys.getwindowsversion()[3] >= 2) + +def relpath(path, start=curdir): + """Return a relative version of a path""" + + if not path: + raise ValueError("no path specified") + start_list = abspath(start).split(sep) + path_list = abspath(path).split(sep) + if start_list[0].lower() != path_list[0].lower(): + unc_path, rest = splitunc(path) + unc_start, rest = splitunc(start) + if bool(unc_path) ^ bool(unc_start): + raise ValueError("Cannot mix UNC and non-UNC paths (%s and %s)" + % (path, start)) + else: + raise ValueError("path is on drive %s, start on drive %s" + % (path_list[0], start_list[0])) + # Work out how much of the filepath is shared by start and path. + for i in range(min(len(start_list), len(path_list))): + if start_list[i].lower() != path_list[i].lower(): + break + else: + i += 1 + + rel_list = [pardir] * (len(start_list)-i) + path_list[i:] + return join(*rel_list) |