Python如何批量获取文件夹的大小并保存

作者:Johnthegreat 时间:2023-10-10 19:49:37 

很多时候,查看一个文件夹下的每个文件大小可以轻易的做到,因为文件后面就是文件尺寸,但是如果需要查看一个文件夹下面所有的文件夹对应的尺寸,就发现需要把鼠标放到对应的文件夹上,稍等片刻才会出结果。

有时候,我们需要查看几十个甚至于上百个文件夹,找出包含文件最多,空间占用最大的那个,就比较麻烦了。这段代码是我以前的代码,可以按大小排序输出文件夹大小到txt文件,供使用的方便。

格式化当时花了很长时间,最后发现使用‘YaHei.Consolas'字体可以解决,对齐后输出结果看起来还算舒服。

上代码:


import os
import datetime

def get_folder_size(path):
 folder_size = 0

if not os.path.exists(path):
   return folder_size

if os.path.isfile(path):
   folder_size = os.path.getsize(path)
   return folder_size
 try:
   if os.path.isdir(path):
     with os.scandir(path) as directory_lists:
       for directory_list in directory_lists:
         if directory_list.is_dir():
           sub_folder_size = get_folder_size(directory_list.path) # 递归获取大小
           folder_size += sub_folder_size
         elif directory_list.is_file():
           file_size = os.path.getsize(directory_list.path)
           folder_size += file_size

return folder_size
 except:
   pass

# 以下主要是为了格式化输出
def get_file_length(file_name):
 characters = list(file_name)
 ascii_length = 0
 utf8_length = 0

for character in characters:
   if ord(character) < 128:
     ascii_length += 1
   else:
     utf8_length += 2

return ascii_length + utf8_length

def main(basedir):
 with os.scandir(basedir) as dirs:
   directory_size = []
   for dir in dirs:
     try:
       if not dir.is_file():
         dirsize = round(get_folder_size(dir.path) / 1000000) # return the file size in Mb
         resformat = [dir.name, dirsize]
         directory_size.append(resformat)
     except:
       pass
   results = sorted(directory_size, key=lambda x: x[1], reverse=True) # return a list ordered by size
   results = [[i[0], '文件夹大小:' + str(i[1]) + ' Mb'] for i in results]

with open(basedir + os.sep + datetime.date.today().isoformat() + '.txt', 'a+') as f:
     for result in results:
       # 按照50的宽度格式化输出结果
       len1 = 50 - get_file_length(result[0]) + len(result[0])
       len2 = 25 - get_file_length(result[1]) + len(result[1])
       f.writelines('{:<{len1}s} {:>{len2}s}\n'.format(result[0], result[1], len1=len1, len2=len2))
     print('The result was successfully saved in the directory with date as file name.')

if __name__ == "__main__":
 basedir = input("Please input the directory you would like to know the sizes: ")
 main(basedir)

如果输入相应的文件夹路径,输出结果如下:

Python如何批量获取文件夹的大小并保存

Python如何批量获取文件夹的大小并保存

有时间我再简化一下代码,目前先这样。

来源:https://www.cnblogs.com/johnthegreat/p/12591502.html

标签:Python,获取,文件夹,大小
0
投稿

猜你喜欢

  • Python利用matplotlib实现制作动态条形图

    2021-06-11 05:29:15
  • Python面向对象进阶学习

    2021-12-18 15:18:12
  • Python from import导包ModuleNotFoundError No module named找不到模块问题解决

    2023-07-27 20:06:53
  • VueX浏览器刷新如何实现保存数据

    2024-04-30 10:24:35
  • vue.js实现日历插件使用方法详解

    2024-05-13 09:38:43
  • 基于Python实现ComicReaper漫画自动爬取脚本过程解析

    2021-07-25 21:45:45
  • 正确理解python迭代器与生成器

    2022-09-14 22:55:57
  • K最近邻算法(KNN)---sklearn+python实现方式

    2023-09-14 15:29:31
  • javascript中的面向对象

    2024-04-18 10:54:33
  • PHP桥接模式Bridge Pattern的优点与实现过程

    2023-05-25 06:53:44
  • Python机器学习pytorch交叉熵损失函数的深刻理解

    2021-12-11 06:09:40
  • 一次Mysql死锁排查过程的全纪录

    2024-01-16 20:35:53
  • 如何绕过ODBC直接访问SQL Server?

    2010-05-18 18:13:00
  • 用Django实现一个可运行的区块链应用

    2022-07-17 22:26:31
  • Python Matplotlib绘制动画的代码详解

    2022-08-19 20:21:03
  • Go实现基于RSA加密算法的接口鉴权

    2024-05-10 13:56:33
  • 没有SQL Server数据库时如何打开.MDF文件

    2024-01-15 05:58:52
  • MySQL多表查询的具体实例

    2024-01-22 00:13:20
  • 关于MySQL的体系结构及存储引擎图解

    2024-01-20 14:52:46
  • python 简单搭建阻塞式单进程,多进程,多线程服务的实例

    2021-01-18 11:00:35
  • asp之家 网络编程 m.aspxhome.com