假设目录结构为:
âââ 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))])