如何用os.walk统计目录所有层级子文件夹总数及子目录大小?
统计目录子文件夹(全层级)、文件总数及目录大小
问题分析
原代码中len(next(os.walk(itempath, level + 1))[1])仅能获取当前目录的直接子文件夹数量,因为next(os.walk(...))只返回当前目录的信息,不会遍历深层子目录。同时原get_size函数的递归逻辑存在重复累加问题,每次递归传入当前total_size会导致计算结果错误。
修改后的完整代码
import os def get_dir_stats(source): """递归统计目录的总大小、所有层级文件夹数、文件数""" total_size = 0 folder_count = 0 file_count = 0 for item in os.listdir(source): itempath = os.path.join(source, item) if os.path.isfile(itempath): total_size += os.path.getsize(itempath) file_count += 1 elif os.path.isdir(itempath): # 递归统计子目录的信息 sub_size, sub_folders, sub_files = get_dir_stats(itempath) total_size += sub_size folder_count += 1 + sub_folders # 当前子目录算1个,加上它的子文件夹数 file_count += sub_files return total_size, folder_count, file_count def walk_recursive(directory, level=0): """遍历并输出指定目录下各子目录的统计信息""" # 获取当前目录的直接子目录列表 for dir_name in next(os.walk(directory))[1]: dir_path = os.path.join(directory, dir_name) # 获取当前子目录的完整统计数据 total_size, folder_count, file_count = get_dir_stats(dir_path) # 格式化路径显示 display_path = dir_name if level == 0 else f"\\{dir_name}" # 格式化输出:缩进、大小(MB)、路径、文件夹数、文件数 indent = " " * level size_mb = total_size / 1048576 # 转换为MB(1MB=1024*1024字节) print(f"{indent}{size_mb:6.2f} MB {display_path} | 文件夹总数: {folder_count} | 文件总数: {file_count}") # 递归遍历下一层级目录(如果需要显示子目录的统计信息) walk_recursive(dir_path, level + 1) # 替换为你的目标目录路径 target_directory = r"<put_your_dir_path_here>" walk_recursive(target_directory)
代码说明
get_dir_stats函数:- 递归遍历目标目录下所有文件和子目录,一次遍历同时统计大小、文件夹数、文件数,提升效率
- 统计文件夹时,将当前子目录算作1个,再累加其内部所有层级的子文件夹数量,实现全层级统计
walk_recursive函数:- 按层级缩进显示目录信息,格式化输出保留2位小数的MB大小
- 递归处理深层子目录,支持嵌套显示所有层级的统计结果
- 关键修复:
- 移除原
get_size函数中错误的递归参数传递,改为内部累计逻辑,避免重复计算 - 通过递归遍历实现全层级的文件夹和文件统计,不再局限于顶层目录
- 移除原
内容的提问来源于stack exchange,提问作者Carl S
相关产品推荐
相关产品推荐

