[英]How to search upwards through directories? Can I os.walk upwards to the root of the filesystem?
我正在尝试搜索特定目录,从给定目录开始但向上,而不是像 os.walk 中那样向下。 例如,这个 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
所以,给定这样一个谓词,告诉我们是否找到了我们需要的目录,我将如何从给定路径向上搜索,例如
os_walk_upwards(os.path.abspath("."), is_alire_root)
会告诉我们当前目录或它上面的任何目录是否包含 alire/*.toml? 尽管 os_walk_upwards 可用于各种搜索,但我特意寻找可以在Gnatstudio中用作插件的东西。
对于 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))
但是 Gnatstudio 使用 python 2.7.16,所以这行不通。 相反,使用:
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.