要按层级分组获取文件夹名称或路径,可以按照以下步骤进行:
方法思路
- 广度优先搜索(BFS):逐层遍历文件夹结构,确保每个层级的文件夹被正确分组。
- 层级记录:使用队列记录当前处理的路径及其层级,每次处理完当前层后进入下一层。
- 分组存储:将同一层级的文件夹路径或名称存储在对应的列表或字典中。
解决代码
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]对应第二层级,依此类推。
注意事项:
- 跳过无权限访问的目录,避免程序中断。
- 使用BFS确保层级遍历顺序正确。
- 结果按层级顺序排列,即使某些层级为空(例如中间层级没有文件夹)。
示例输出
假设目录结构如下:
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']