[英]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.