Search code examples
pythonpython-os

How can i get a path relative from an other?


Visualization I have a path1 relative from a path2 and I want to get this path1 from my script which isn't path1 or path2. I know the absolute path of path2.


Solution

  • made my own funtion

    import pathlib
    
    def convert_path(path, org_path):
        org_path = pathlib.Path(org_path).parent # need the folder where my file is
        for element in path.split(os.path.sep):
            if element == "..":
                org_path = org_path.parent
            else:
                org_path = org_path.joinpath(element)
        return str(org_path)