我的知识记录

Python 统计文件夹大小:找出最占空间的文件

import os
 
def folder_size(path):
    total = 0
    for root, _, files in os.walk(path):
        for name in files:
            try:
                total += os.path.getsize(os.path.join(root, name))
            except OSError:
                pass
    return total
 
def human(n):
    for unit in ['B', 'KB', 'MB', 'GB', 'TB']:
        if n < 1024:
            return f"{n:.2f} {unit}"
        n /= 1024
 
def top_files(folder, top=20):
    items = []
    for root, _, files in os.walk(folder):
        for name in files:
            path = os.path.join(root, name)
            try:
                items.append((os.path.getsize(path), path))
            except OSError:
                pass
    items.sort(reverse=True)
    for size, path in items[:top]:
        print(f"{human(size):>10}  {path}")
 
top_files('D:/', top=20)

Python 统计文件夹大小:找出最占空间的文件

标签:

更新时间:2026-09-14 13:42:32

上一篇:Python 找出重复文件:自动清理占空间的大文件

下一篇: Python 生成词云:一篇文章生成漂亮词云图