Python Forum

Full Version: function wanted: resolve relative path
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
i would like a function, that given paths to 2 directories, in either absolute or relative form, determines the path to reference directory 1 from directory 2 (or visa-versa). this could mean a lot of "../" in the result. the intended use is making relative symlinks. if the 2 directories are the same directory, the result obviously should be ".".

a plus would be support for the target to be any file system object type, not just a directory. another plus is not requiring either to actually exist, if the paths can still be resolved to absolute or to each other somehow (they might be created in the future ... such as generating a script that creates the objects and a symlink between them.
Here is a first attempt with pathlib
from pathlib import Path

d0 = Path('/home/me/project/spam/doc')
d1 = Path('/home/me/lib/spam')
d2 = d1 / 'foo' / 'bar'

class Out:
    def __lshift__(self, *args):
        for a in args:
            print(a, end=' ')
        return self
cout = Out()
endl = '\n'

def compute_link(path, base):
    b = base
    res = Path()
    while True:
        try:
            r = path.relative_to(b)
        except ValueError:
            b, old = b.parent, b
            if b == old:
                raise
            res /= '..'
        else:
            return res / r
        
cout << 'found' << compute_link(d1, d0) << endl
sorry, i don't understand line 29. it looks like some odd form or variant of c++.
(Sep-05-2018, 05:08 AM)Skaperen Wrote: [ -> ]sorry, i don't understand line 29
Then use print('found', compute_link(d1, d0)) Rolleyes
so python includes some c++ stuff? what else?

* Skaperen never did like c++