【发布时间】: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将是这种方法的更好选择。