简体   繁体   English

如何向上搜索目录? 我可以 os.walk 向上到文件系统的根目录吗?

[英]How to search upwards through directories? Can I os.walk upwards to the root of the filesystem?

I am trying to search for a specific directory, starting from a given directory but going upwards, rather than down as in os.walk.我正在尝试搜索特定目录,从给定目录开始但向上,而不是像 os.walk 中那样向下。 For example, this function returns whether or not the given directory is the root of an Alire project - which just means it contains alire/*.toml:例如,这个 function 返回给定目录是否是Alire项目的根目录 - 这只是意味着它包含 alire/*.toml:

''' Check if this directory contains a 'alire/*.toml' file '''
def is_alire_root(dir):
    dir = dir / "alire"
    if dir.is_dir():
        for x in dir.iterdir():
            if x.suffixes == [".toml"]:
                return True
        return False
    else:
        return False

So, given such a predicate that tells us whether we have found the directory we need, how would I search upwards from a given path, so that eg所以,给定这样一个谓词,告诉我们是否找到了我们需要的目录,我将如何从给定路径向上搜索,例如

os_walk_upwards(os.path.abspath("."), is_alire_root)

Will tell us if the current directory or any directories above it contain alire/*.toml?会告诉我们当前目录或它上面的任何目录是否包含 alire/*.toml? Although os_walk_upwards could be used for various searches, I am specifically looking for something that will work as a plugin in Gnatstudio .尽管 os_walk_upwards 可用于各种搜索,但我特意寻找可以在Gnatstudio中用作插件的东西。

For python version >= 3.4 we can use pathlib :对于 python 版本 >= 3.4 我们可以使用pathlib

import os.path
from pathlib import Path

def is_alire_root(dir):
    (... as above ...)

''' Search upwards from path for a directory matching the predicate '''
def os_walk_upwards(directory_predicate, path=Path(os.path.abspath("."))):
    if directory_predicate(path):
        return True
    else:
        parent = path.parent
        if parent == path:
            return False  # reached root of filesystem
        return directory_predicate(parent)

print(os_walk_upwards(is_alire_root))

But Gnatstudio uses python 2.7.16, so that isn't going to work.但是 Gnatstudio 使用 python 2.7.16,所以这行不通。 Instead, use:相反,使用:

import os.path

''' Check if this directory contains a 'alire/*.toml' file '''
def is_alire_root(dir):
    dir = os.path.join(dir, "alire")
    if os.path.isdir(dir):
        for x in os.listdir(dir):
            if os.path.splitext(x)[1] == ".toml":  # will also match e.g. *.tar.gz.toml
                return True
        return False
    else:
        return False

''' Check if this or any parent directories are alire_root directories '''
def os_walk_upwards(directory_predicate, path=os.path.abspath(".")):
    if directory_predicate(path):
        return True
    else:
        parent = os.path.dirname(path)
        if parent == path:
            return False  # reached root of filesystem
        return directory_predicate(parent)

print(os_walk_upwards(is_alire_root))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM