Return a relative version of a path
(path, start=None)
| 739 | sys.getwindowsversion()[3] >= 2) |
| 740 | |
| 741 | def relpath(path, start=None): |
| 742 | """Return a relative version of a path""" |
| 743 | path = os.fspath(path) |
| 744 | if isinstance(path, bytes): |
| 745 | sep = b'\\' |
| 746 | curdir = b'.' |
| 747 | pardir = b'..' |
| 748 | else: |
| 749 | sep = '\\' |
| 750 | curdir = '.' |
| 751 | pardir = '..' |
| 752 | |
| 753 | if start is None: |
| 754 | start = curdir |
| 755 | |
| 756 | if not path: |
| 757 | raise ValueError("no path specified") |
| 758 | |
| 759 | start = os.fspath(start) |
| 760 | try: |
| 761 | start_abs = abspath(normpath(start)) |
| 762 | path_abs = abspath(normpath(path)) |
| 763 | start_drive, start_rest = splitdrive(start_abs) |
| 764 | path_drive, path_rest = splitdrive(path_abs) |
| 765 | if normcase(start_drive) != normcase(path_drive): |
| 766 | raise ValueError("path is on mount %r, start on mount %r" % ( |
| 767 | path_drive, start_drive)) |
| 768 | |
| 769 | start_list = [x for x in start_rest.split(sep) if x] |
| 770 | path_list = [x for x in path_rest.split(sep) if x] |
| 771 | # Work out how much of the filepath is shared by start and path. |
| 772 | i = 0 |
| 773 | for e1, e2 in zip(start_list, path_list): |
| 774 | if normcase(e1) != normcase(e2): |
| 775 | break |
| 776 | i += 1 |
| 777 | |
| 778 | rel_list = [pardir] * (len(start_list)-i) + path_list[i:] |
| 779 | if not rel_list: |
| 780 | return curdir |
| 781 | return join(*rel_list) |
| 782 | except (TypeError, ValueError, AttributeError, BytesWarning, DeprecationWarning): |
| 783 | genericpath._check_arg_types('relpath', path, start) |
| 784 | raise |
| 785 | |
| 786 | |
| 787 | # Return the longest common sub-path of the sequence of paths given as input. |