代码之家  ›  专栏  ›  技术社区  ›  Dr. Strangelove

获取从当前到第n个深度的目录

  •  1
  • Dr. Strangelove  · 技术社区  · 5 年前

    假设目录结构为:

    ├── parent_1
    │   ├── child_1
    │   │   ├── sub_child_1
    │   │   │   └── file_1.py
    │   │   └── file_2.py
    │   └── file_3.py
    ├── parent_2
    │   └── child_2
    │       └── file_4.py
    └── file_5.py
    
    

    parents = ["parent_1", "parent_2"]
    children = ["child_1", "child_2"]
    

    请注意,文件和 sub_child_1 不包括在内。

    this ,我会写:

    parents = []
    children = []
    for root, dir, files in os.walk(path, topdown=True):
        depth = root[len(path) + len(os.path.sep):].count(os.path.sep)
        if depth == 0:
            parents.append(dir)
        elif depth == 1:
            children.append(dir)
    

    更新1

    我还试了一个 listdir -基于策略的方法:

    parents = [f for f in listdir(root) if isdir(join(root, f))]
    children = []
    for p in parents:
        children.append([f for f in listdir(p) if isdir(join(root, p, f))])
    
    1 回复  |  直到 5 年前
        1
  •  2
  •   blhsing    5 年前

    您可以清除由返回的目录 os.walk 要防止它在达到所需深度时移动得更深,请执行以下操作:

    for root, dirs, _ in os.walk(path, topdown=True):
        if root == path:
            continue
        parents.append(root)
        children.extend(dirs)
        dirs.clear()
    
    推荐文章