【问题标题】:Get directories from the current to the n-th depth获取当前到第n个深度的目录
【发布时间】:2021-10-11 00:21:52
【问题描述】:

假设一个目录结构为:

├── 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))])

【问题讨论】:

  • 您是否也尝试过基于listdir 的方法,因为您有固定数量的要查看的级别?
  • 感谢您的建议,是的,我尝试了这种方法,请参阅更新后的问题。不过,第二个循环对我来说并不那么令人兴奋。
  • @KarlKnechtel os.listdir 的问题是效率低下,因为对于它返回的每条记录,您必须通过单独的系统调用 os.path.isdir 来检查它是否是一个目录,这非常慢在处理大型目录时。 os.scandir 将是这种方法的更好选择。

标签: python directory path


【解决方案1】:

您可以清除os.walk返回的目录,以防止它在达到您想要的深度时遍历更深:

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

【讨论】:

  • 更正:children.extend(dirs) -> children.extend(dirs.copy())
  • 没有必要复制dirs,因为list.extend 方法已经将dirs 的值复制到children
  • 我使用的是append,在.clear() 之后丢失了信息。感谢您的澄清。
猜你喜欢
  • 2013-06-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-20
  • 2013-01-29
  • 2016-07-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多