Jerrit
Jerrit

Reputation: 149

Is there a way to use Pathlib to traverse parents folders until a name matches?

I was discussing with a colleague if there is a built-in (or clean) way to use Pathlib to traverse through an arbitrary Path to find a given parent folder, for example the root of your repository (which may differ per user that has a local copy of said repo). I simulated the desired behaviour below:

from pathlib import Path

def find_parent(path: Path, target_parent: str) -> Path:
    for part in path.parts[::-1]:
        if part != target_parent:
            path = path.parent
        else:
            break
    return path

path = Path("/some/arbitrarily/long/path/ROOT_FOLDER/subfolder1/subfolder2/file.py")
root = find_parent(path, "ROOT_FOLDER")
assert root == Path("/some/arbitrarily/long/path/ROOT_FOLDER")

Is there an easier way to achieve this?

Upvotes: 1

Views: 1201

Answers (2)

Chris
Chris

Reputation: 136918

You could iterate over path.parents (plural) directly, which makes this a bit cleaner:

def find_parent(path: Path, target_parent: str) -> Path | None:
    # `path.parents` does not include `path`, so we need to prepend it if it is
    # to be considered
    for parent in [path] + list(path.parents):
        if parent.name == target_parent:
            return parent

(No need for the else clause.)

Upvotes: 5

Jerrit
Jerrit

Reputation: 149

Based on @Chris's answer, I found the following one-liner is what I am after:

root = [parent for parent in path.parents if parent.name == "ROOT_FOLDER"][0]


Updated to root = next((parent for parent in path.parents if parent.name == "ROOT_FOLDER"), None) based on @SUTerliakov's suggestion.

Upvotes: 3

Related Questions