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

Time:05-05

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

CodePudding user response:

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
  • Related