Skip to content

Instantly share code, notes, and snippets.

@Songbird0
Created November 30, 2017 19:52
Show Gist options
  • Save Songbird0/b5a5657e0eb92afa6d76427fec065df4 to your computer and use it in GitHub Desktop.
Save Songbird0/b5a5657e0eb92afa6d76427fec065df4 to your computer and use it in GitHub Desktop.
CheatSheet: Create a relative path from an absolute or another relative path.
#!/usr/bin/python
# -*- coding: utf-8 -*-
import pathlib
def create_relative_path(initial_path: pathlib.Path, new_root: str) -> pathlib.Path:
"""Creates a new path from the initial path.
Example:
your_path = pathlib.Path('/foo/bar/baz/bang')
create_relative_path(your_path, 'bar') returns -> Windows|UnixPath('bar/baz/bang')
If `new_root` does not exist, `create_relative_path` will return `None`.
"""
stringified_initial_path = initial_path.__str__()
new_root_index = stringified_initial_path.index(new_root)
if new_root_index > 0:
return pathlib.Path(stringified_initial_path[new_root_index:])
else:
return None
my_path = pathlib.Path('/foo/bar/baz/bang')
new_path = create_relative_path(my_path, 'baz')
import os
if os.name == 'nt':
assert new_path.__str__() == 'baz\\bang'
else:
assert new_path.__str__() == 'baz/bang'
print('new_path="{}"'.format(new_path))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment