使用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')
相关推荐
Doc.S37 分钟前
【保姆级教程】在AutoDL容器中部署EGO-Planner,实现无人机动态避障规划
人工智能·python·信息可视化·机器人
骚戴39 分钟前
PDF或Word转图片(多线程+aspose+函数式接口)
java·开发语言
姓蔡小朋友41 分钟前
SpringDataRedis
java·开发语言·redis
Predestination王瀞潞1 小时前
Python3:Eighth 函数
开发语言·python
蒋星熠1 小时前
多模态技术深度探索:融合视觉与语言的AI新范式
人工智能·python·深度学习·机器学习·分类·数据挖掘·多分类
夜晚中的人海1 小时前
【C++】分治-快速排序算法习题
开发语言·c++·排序算法
xier_ran1 小时前
Python从入门到精通:(2)Python 核心进阶教程从数据结构到面向对象
linux·windows·python·microsoft
爱编程的鱼1 小时前
想学编程作为今后的工作技能,学哪种语言适用性更强?
开发语言·算法·c#·bug
yugi9878381 小时前
基于MATLAB的心电信号去噪
开发语言·matlab
国服第二切图仔2 小时前
Rust入门开发之Rust中如何实现面向对象编程
开发语言·后端·rust