python - 如何获取包含受 Python 深度限制的特定文件的所有目录?

我想做什么

我正在尝试获取包含文件 y 的 x 深度的子目录列表,例如:

root/
root/one/
root/one/README.md
root/two/subdir/
root/two/subdir/README.md
root/three/

在上面的树中,我试图识别所有包含文件 README.md 的 x 级别的子目录。

  • 如果x = 1,它应该返回root/one/
  • 如果x = 2,它应该返回root/one/root/two/subdir

我尝试过的

我能找到的大多数答案都使用 os.walk 来遍历目录和识别文件。虽然这有效,但它不允许对递归进行深度限制。一些解决方法包括 creating a depth-limited os.walk function和其他人使用 glob patterns to specify depth such as */*/* for depth of 3或 generated glob pattern .虽然这两种方法都有效,但我想知道是否存在更简洁的方法来解决我的问题?

os.walk 破解

def walklevel(some_dir, level=1):
    some_dir = some_dir.rstrip(os.path.sep)
    assert os.path.isdir(some_dir)
    num_sep = some_dir.count(os.path.sep)
    for root, dirs, files in os.walk(some_dir):
        yield root, dirs, files
        num_sep_this = root.count(os.path.sep)
        if num_sep + level <= num_sep_this:
            del dirs[:]

glob 破解

def fileNamesRetrieve(top, maxDepth, fnMask):
    someFiles = []
    for d in range(1, maxDepth+1):
        maxGlob = "/".join("*" * d)
        topGlob = os.path.join(top, maxGlob)
        allFiles = glob.glob(topGlob)

代码示例

def get_subdirs(dir):
    file = "README.md"
    subdirs = []
    # something like this looping through subdirs
    for subdir in subdirs(dir, depth=1):
        if any(f for f in subdirs.files if f = file)
            subdirs.append(subdir)
    return subdirs

问题

我该如何解决这个问题?

最佳答案

试试这个:

import os

def findDirWithFileInLevel(path, file, level=1):
    c = path.count(os.sep)
    for root, dirs, files in os.walk(path):
        for name in files:
            if name == file and root.count(os.sep) - c - 1 <= level:
                yield root
                
for i in findDirWithFileInLevel(".\\root", "readme.txt", 2):
    print(i)

逻辑类似于您的os.walk hack,只需将路径分隔符的数量与os.walk中的level进行比较并返回路径(我的代码中的 root)。

c是初始路径中路径分隔符的个数。

https://stackoverflow.com/questions/72441880/

相关文章:

flutter - 如何在 ListView.builder flutter 中正确使用 findC

node.js - 在 whatsapp 云 API 的模板标题中添加示例图像

typescript - 一起使用 Typescript 可变元组类型和 Javascript Sp

rust - "the size for values of type cannot be know

reactjs - RTK 查询维持 `isLoading` 缓存失效后自动重新获取

python - 通过多进程生成的对象标识

java - 这个官方 Xml 模式是否无效或者是 Jaxb 的错误限制

kubernetes - 由于 'No such file or directory',Kubect

f# - 使用 Foq 模拟 Microsoft.Extensions.Logging.ILogge

node.js - Pug - 包括带有 "include"关键字的 C 代码