使用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')
相关推荐
chao_7891 小时前
二分查找篇——搜索旋转排序数组【LeetCode】一次二分查找
数据结构·python·算法·leetcode·二分查找
烛阴2 小时前
Python装饰器解除:如何让被装饰的函数重获自由?
前端·python
Boilermaker19922 小时前
【Java EE】Mybatis-Plus
java·开发语言·java-ee
aramae2 小时前
C++ -- STL -- vector
开发语言·c++·笔记·后端·visual studio
Tony小周2 小时前
实现一个点击输入框可以弹出的数字软键盘控件 qt 5.12
开发语言·数据库·qt
noravinsc2 小时前
django 一个表中包括id和parentid,如何通过parentid找到全部父爷id
python·django·sqlite
lixzest2 小时前
C++ Lambda 表达式详解
服务器·开发语言·c++·算法
ajassi20002 小时前
开源 python 应用 开发(三)python语法介绍
linux·python·开源·自动化
沉默媛3 小时前
如何安装python以及jupyter notebook
开发语言·python·jupyter
_Chipen3 小时前
C++基础问题
开发语言·c++