使用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')
相关推荐
麦麦鸡腿堡31 分钟前
Java的动态绑定机制(重要)
java·开发语言·算法
时间之里32 分钟前
【c++】:Lambda 表达式介绍和使用
开发语言·c++
zy_destiny38 分钟前
【工业场景】用YOLOv8实现抽烟识别
人工智能·python·算法·yolo·机器学习·计算机视觉·目标跟踪
Tiger_shl44 分钟前
C# 预处理指令 (# 指令) 详解
开发语言·c#
(●—●)橘子……1 小时前
记力扣2009:使数组连续的最少操作数 练习理解
数据结构·python·算法·leetcode
@Kerry~1 小时前
phpstudy .htaccess 文件内容
java·开发语言·前端
CRMEB系统商城1 小时前
CRMEB多商户系统(PHP)v3.3正式发布,同城配送上线[特殊字符]
java·开发语言·小程序·php
nueroamazing1 小时前
PPT-EA:PPT自动生成器
vue.js·python·语言模型·flask·大模型·项目·ppt
sali-tec2 小时前
C# 基于halcon的视觉工作流-章45-网格面划痕
开发语言·算法·计算机视觉·c#
一壶浊酒..2 小时前
python 爬取百度图片
开发语言·python·百度