获取从当前到第n层的目录
Get directories from the current to the n-th depth
假设目录结构为:
├── 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))])
您可以清除 os.walk
返回的目录,以防止它在达到您想要的深度时进一步遍历:
for root, dirs, _ in os.walk(path, topdown=True):
if root == path:
continue
parents.append(root)
children.extend(dirs)
dirs.clear()
假设目录结构为:
├── 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))])
您可以清除 os.walk
返回的目录,以防止它在达到您想要的深度时进一步遍历:
for root, dirs, _ in os.walk(path, topdown=True):
if root == path:
continue
parents.append(root)
children.extend(dirs)
dirs.clear()