You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python获取主目录下一级子目录的总大小(含子子目录内容)

解决Python只统计主目录一级子目录总大小的问题

看起来你之前的代码应该是用了os.walk()遍历所有层级的目录,导致连深层子目录的大小也单独输出了对吧?别担心,我们只需要调整逻辑,只处理主目录下的直接子目录,然后对每个子目录递归计算它的完整大小(包含所有内部文件和子目录)就可以了。

下面是两种实现方式,你可以根据习惯选择:

方式一:使用os模块(传统写法)

import os

def get_total_directory_size(dir_path):
    """递归计算目录的总大小,跳过符号链接"""
    total_size = 0
    for root, _, files in os.walk(dir_path):
        for file in files:
            file_full_path = os.path.join(root, file)
            # 跳过符号链接避免统计重复或错误
            if not os.path.islink(file_full_path):
                try:
                    total_size += os.path.getsize(file_full_path)
                except OSError:
                    # 处理权限不足或文件已删除的情况
                    print(f"无法访问文件: {file_full_path},已跳过")
    return total_size

# 替换成你的主目录路径
main_directory = "/home/your_username/main_folder"

# 遍历主目录下的直接子目录
for entry in os.scandir(main_directory):
    if entry.is_dir(follow_symlinks=False):
        dir_size = get_total_directory_size(entry.path)
        # 转换为更易读的MB单位(也可以换成GB:dir_size / (1024**3))
        readable_size = dir_size / (1024 * 1024)
        print(f"- {entry.name}: {readable_size:.2f} MB")

方式二:使用pathlib(Python 3.4+ 推荐写法)

pathlib提供了更面向对象的路径操作,代码更简洁:

from pathlib import Path

def calculate_dir_total_size(dir_path: Path) -> int:
    """计算目录总大小,跳过符号链接"""
    total_size = 0
    # rglob('*') 递归遍历所有文件
    for file_path in dir_path.rglob('*'):
        if file_path.is_file() and not file_path.is_symlink():
            try:
                total_size += file_path.stat().st_size
            except OSError:
                print(f"无法访问文件: {file_path},已跳过")
    return total_size

# 替换成你的主目录路径
main_dir = Path("/home/your_username/main_folder")

# 只处理主目录下的直接子目录
for child_dir in main_dir.iterdir():
    if child_dir.is_dir() and not child_dir.is_symlink():
        total_size = calculate_dir_total_size(child_dir)
        # 转换为GB单位
        readable_size = total_size / (1024 ** 3)
        print(f"- {child_dir.name}: {readable_size:.2f} GB")

关键逻辑说明:

  1. 只处理一级子目录:用os.scandir()(或pathlib.Path.iterdir())遍历主目录,只筛选出is_dir()的条目,这样就不会触及深层子目录。
  2. 递归计算总大小:对每个一级子目录,用os.walk()或rglob('*')递归遍历所有内部文件,累加它们的大小,得到整个子目录的总占用空间。
  3. 异常处理:加入了对权限问题或文件缺失的处理,避免程序中途崩溃。

这样运行后,就只会输出你指定主目录下的直接子目录名称和它们的完整大小,不会再出现深层子目录的单独输出啦。

内容的提问来源于stack exchange,提问作者Sushant

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 04:13:01