[英]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).我正在与一位同事讨论是否有一种内置(或干净)的方式来使用 Pathlib 遍历任意路径以查找给定的父文件夹,例如存储库的根目录(每个用户可能有所不同)所述回购协议的本地副本)。 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?有没有更简单的方法来实现这一目标?
You could iterate over path.parents
(plural) directly, which makes this a bit cleaner:您可以直接遍历
path.parents
(复数),这样会更简洁一些:
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.) (不需要 else 子句。)
Based on @Chris's answer, I found the following one-liner is what I am after:根据@Chris 的回答,我发现下面的一句话就是我所追求的:
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.根据@SUTerliakov 的建议更新为
root = next((parent for parent in path.parents if parent.name == "ROOT_FOLDER"), None)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.