Return a relative version of a path
(path, start=None)
| 516 | supports_unicode_filenames = (sys.platform == 'darwin') |
| 517 | |
| 518 | def relpath(path, start=None): |
| 519 | """Return a relative version of a path""" |
| 520 | |
| 521 | path = os.fspath(path) |
| 522 | if not path: |
| 523 | raise ValueError("no path specified") |
| 524 | |
| 525 | if isinstance(path, bytes): |
| 526 | curdir = b'.' |
| 527 | sep = b'/' |
| 528 | pardir = b'..' |
| 529 | else: |
| 530 | curdir = '.' |
| 531 | sep = '/' |
| 532 | pardir = '..' |
| 533 | |
| 534 | if start is None: |
| 535 | start = curdir |
| 536 | else: |
| 537 | start = os.fspath(start) |
| 538 | |
| 539 | try: |
| 540 | start_tail = abspath(start).lstrip(sep) |
| 541 | path_tail = abspath(path).lstrip(sep) |
| 542 | start_list = start_tail.split(sep) if start_tail else [] |
| 543 | path_list = path_tail.split(sep) if path_tail else [] |
| 544 | # Work out how much of the filepath is shared by start and path. |
| 545 | i = len(genericpath._commonprefix([start_list, path_list])) |
| 546 | |
| 547 | rel_list = [pardir] * (len(start_list)-i) + path_list[i:] |
| 548 | if not rel_list: |
| 549 | return curdir |
| 550 | return sep.join(rel_list) |
| 551 | except (TypeError, AttributeError, BytesWarning, DeprecationWarning): |
| 552 | genericpath._check_arg_types('relpath', path, start) |
| 553 | raise |
| 554 | |
| 555 | |
| 556 | # Return the longest common sub-path of the sequence of paths given as input. |