举报
要按层级分组获取文件夹名称或路径,可以按照以下步骤进行:
import os
from collections import deque
def group_folders_by_level(root_dir, include_full_path=True):
"""按层级分组获取文件夹名称或路径
Args:
root_dir (str): 根目录路径
include_full_path (bool): 是否返回完整路径,默认为True;False时仅返回文件夹名
Returns:
list: 分组的列表,每个元素是该层级的所有文件夹路径或名称
"""
groups = {}
# 使用队列进行BFS,初始为根目录的子文件夹(层级1)
queue = deque([(root_dir, 1)])
while queue:
current_path, current_level = queue.popleft()
try:
entries = os.listdir(current_path)
except PermissionError:
continue # 跳过无权限访问的目录
for entry in entries:
full_path = os.path.join(current_path, entry)
if os.path.isdir(full_path):
# 根据参数决定存储名称或完整路径
name = full_path if include_full_path else entry
if current_level not in groups:
groups[current_level] = []
groups[current_level].append(name)
# 将子目录加入队列,层级+1
queue.append((full_path, current_level + 1))
# 按层级顺序整理结果(避免层级不连续)
max_level = max(groups.keys()) if groups else 0
sorted_groups = []
for level in range(1, max_level + 1):
sorted_groups.append(groups.get(level, []))
return sorted_groups
# 示例用法
if __name__ == "__main__":
root = '/path/to/your/root/directory'
grouped = group_folders_by_level(root)
for i, folders in enumerate(grouped, 1):
print(f"层级 {i}: {folders}")参数说明:
root_dir:需要遍历的根目录路径。include_full_path:控制返回的是完整路径(True)还是仅文件夹名称(False)。输出结果:
grouped[0]对应第一层级(主文件夹),grouped[1]对应第二层级,依此类推。注意事项:
假设目录结构如下:
root/
├─ A/
│ └─ B/
├─ C/
└─ D/
└─ E/
└─ F/运行代码后输出可能为:
层级 1: ['/root/A', '/root/C', '/root/D']
层级 2: ['/root/A/B', '/root/D/E']
层级 3: ['/root/D/E/F']
举报

问题没太看懂是啥意思,不过如果是获取某个目录下的文件夹名的话上面老哥说的用罗列文件夹控价就可以了
举报
更多回帖