I'm trying to find a readable way to check whether a path is within another path across more than a single level. I can check the immediate parent, but not beyond that so far.
import pathlib
path1 = pathlib.Path('/a/b')
path2 = pathlib.Path('/a/b/c/d')
path2.parent == path1 # <-- this is False, expected.
path2 in path1 # <-- this is False, UNEXPECTED.
Or is the best option to devolve to string comparisons and startwith
checks on absolute paths?
https://docs.python.org/3/library/pathlib.html
Path instances have a parents
attribute that contains a sequence of all ancestors. You can test whether one path is 'in another path' by testing whether it is an ancestor of the other path.
Using your example paths, this is as simple as:
path1 in path2.parents
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With