使用python获取文件和文件夹的大小并排序

使用python获取文件和文件夹的大小并排序

作用

  1. 获取指定目录中文件及文件夹的大小
  2. 按照文件及文件夹大小降序排列
  3. 把结果存到文本文件中

效果


代码

python 复制代码
import os
from collections import defaultdict
import stat

def get_size(start_path='.'):
    """
    递归获取文件夹及其子文件夹和文件的大小(以MB为单位)
    """
    total_size_bytes = 0
    for dirpath, dirnames, filenames in os.walk(start_path):
        for f in filenames:
            fp = os.path.join(dirpath, f)
            # 跳过如果它是符号链接
            if not os.path.islink(fp):
                total_size_bytes += os.path.getsize(fp)
                # 将字节转换为MB
    total_size_mb = total_size_bytes / (1024 * 1024)
    return total_size_mb


def list_files_and_folders(start_path='.'):
    """
    列出文件夹及其子文件夹和文件的大小,并返回字典(以MB为单位)
    """
    sizes = defaultdict(float)

    for dirpath, dirnames, filenames in os.walk(start_path):
        # 排除隐藏的子文件夹
        dirnames[:] = [d for d in dirnames if
                       not os.stat(os.path.join(dirpath, d)).st_file_attributes & stat.FILE_ATTRIBUTE_HIDDEN]

        for f in filenames:
            fp = os.path.join(dirpath, f)
            # 跳过如果它是符号链接或隐藏文件
            if not os.path.islink(fp) and not os.stat(fp).st_file_attributes & stat.FILE_ATTRIBUTE_HIDDEN:
                sizes[fp] = os.path.getsize(fp) / (1024 * 1024)  # 直接转换为MB

        for d in dirnames:
            dp = os.path.join(dirpath, d)
            # 计算子文件夹的大小(以MB为单位),并将其添加到sizes字典中
            sizes[dp] = get_size(dp)

    return sizes


def rank_sizes(sizes):
    """
    根据大小对文件/文件夹进行排名
    """
    return sorted(sizes.items(), key=lambda x: x[1], reverse=True)


def print_ranked_sizes(ranked_sizes, output_file='ranked_sizes.txt'):
    """
    打印排名后的文件/文件夹大小(以MB为单位)并保存到文件
    """
    with open(output_file, 'w', encoding='utf-8') as f:
        for rank, (path, size) in enumerate(ranked_sizes, start=1):
            # 打印到控制台
            print(f"Rank {rank}: {path} - {size:.2f} MB")
            # 写入到文件
            f.write(f"Rank {rank}: {path} - {size:.2f} MB\n")



if __name__ == "__main__":
    start_path = r"C:\BaiduNetdiskDownload"
    sizes = list_files_and_folders(start_path)
    ranked_sizes = rank_sizes(sizes)
    print_ranked_sizes(ranked_sizes, output_file='ranked_sizes.txt')
相关推荐
风逸hhh44 分钟前
python打卡day29@浙大疏锦行
开发语言·前端·python
浩皓素1 小时前
深入理解For循环及相关关键字原理:以Python和C语言为例
c语言·python
英英_1 小时前
详细介绍一下Python连接MySQL数据库的完整步骤
数据库·python·mysql
ᖰ・◡・ᖳ1 小时前
JavaScript:PC端特效--缓动动画
开发语言·前端·javascript·css·学习·html5
水花花花花花1 小时前
GloVe 模型讲解与实战
python·深度学习·conda·pip
C_VuI1 小时前
如何安装cuda版本的pytorch
人工智能·pytorch·python
Star abuse1 小时前
机器学习基础课程-6-课程实验
人工智能·python·机器学习
hy____1231 小时前
C++多态的详细讲解
开发语言·c++
小葡萄20251 小时前
黑马程序员C++2024版笔记 第0章 C++入门
开发语言·c++·笔记
万物此臻1 小时前
C#编写软件添加菜单栏
开发语言·c#