Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check whether a path is in another path using Pathlib?

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.

How can I check for presence of one path in another?

Or is the best option to devolve to string comparisons and startwith checks on absolute paths?

https://docs.python.org/3/library/pathlib.html

like image 590
tarabyte Avatar asked Oct 16 '25 16:10

tarabyte


1 Answers

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
like image 162
Niels Wouda Avatar answered Oct 18 '25 05:10

Niels Wouda



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!