Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading