使用Python计算目录大小? [英] Calculating a directory size using Python?

查看:145
本文介绍了使用Python计算目录大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我重新发明这个特定的轮子之前,有没有人有一个很好的例程来计算使用Python的目录的大小?这将是非常好的,如果例程将格式化大小在Mb / Gb等。

解决方案

这抓住子目录: p>

  import os 
def get_size(start_path ='。'):
total_size = 0
dirpath,dirnames,os.walk中的文件名(start_path):文件名中的f

fp = os.path.join(dirpath,f)
total_size + = os.path.getsize (fp)
return total_size

print get_size()

并使用 os.listdir 不包括子目录):

  import os 
sum(os.path。如果os.path.isfile(f))


$ b $在os.listdir('。' b

参考:



os.p ath.getsize - 给出字节大小



os.walk



更新
要使用 os.path.getsize ,这比使用os.stat()。st_size方法更清楚。



感谢ghostdog74指向这个出来!



os.stat - st_size 以字节为单位给出大小。也可以用于获取文件大小和其他文件相关信息。



更新2015



scandir 可用,可能比 os.walk 方法更快。一个软件包可以从pypi获得,而 os.scandir()将包含在python 3.5中:



< a href =https://pypi.python.org/pypi/scandir =noreferrer> https://pypi.python.org/pypi/scandir


Before i re-invent this particular wheel, has anybody got a nice routine for calculating the size of a directory using Python? It would be very nice if the routine would format the size nicely in Mb/Gb etc.

解决方案

This grabs subdirectories:

import os
def get_size(start_path = '.'):
    total_size = 0
    for dirpath, dirnames, filenames in os.walk(start_path):
        for f in filenames:
            fp = os.path.join(dirpath, f)
            total_size += os.path.getsize(fp)
    return total_size

print get_size()

And a oneliner for fun using os.listdir (Does not include sub-directories):

import os
sum(os.path.getsize(f) for f in os.listdir('.') if os.path.isfile(f))

Reference:

os.path.getsize - Gives the size in bytes

os.walk

Updated To use os.path.getsize, this is clearer than using the os.stat().st_size method.

Thanks to ghostdog74 for pointing this out!

os.stat - st_size Gives the size in bytes. Can also be used to get file size and other file related information.

Update 2015

scandir is available and may be faster than the os.walk method. A package is available from pypi, and os.scandir() is to be included in python 3.5:

https://pypi.python.org/pypi/scandir

这篇关于使用Python计算目录大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆