I'm facing an issue while trying to get relative path to a parent level directory using pathlib but os.path works. How to satisfy the requirement using pathlib APIs?
In [1]: import os
In [2]: p1 = "/a/b/c"
In [3]: p2 = "/a/b/c/d/e"
In [4]: os.path.relpath(p1, p2)
Out[4]: '../..'
But below code throws exception -
In [5]: import pathlib
In [6]: c = pathlib.Path(p1).relative_to(pathlib.Path(p2))
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Cell In[6], line 1
----> 1 c = pathlib.Path(p1).relative_to(pathlib.Path(p2))
File ~/.conda/envs/slm-scratch-experiment/lib/python3.9/pathlib.py:939, in PurePath.relative_to(self, *other)
937 if (root or drv) if n == 0 else cf(abs_parts[:n]) != cf(to_abs_parts):
938 formatted = self._format_parsed_parts(to_drv, to_root, to_parts)
--> 939 raise ValueError("{!r} is not in the subpath of {!r}"
940 " OR one path is relative and the other is absolute."
941 .format(str(self), str(formatted)))
942 return self._from_parsed_parts('', root if n == 1 else '',
943 abs_parts[n:])
ValueError: '/a/b/c' is not in the subpath of '/a/b/c/d/e' OR one path is relative and the other is absolute.