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

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

问题描述

在我重新发明这个特殊的轮子之前,有没有人有一个很好的例程来使用 Python 计算目录的大小?如果例程能够以 Mb/Gb 等格式很好地格式化大小,那就太好了.

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 walks all sub-directories; summing file sizes:

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)
            # skip if it is symbolic link
            if not os.path.islink(fp):
                total_size += os.path.getsize(fp)

    return total_size

print(get_size(), 'bytes')

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

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

参考:

  • os.path.getsize - Gives the size in bytes
  • os.walk
  • os.path.islink

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

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

感谢 ghostdog74 指出这一点!

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

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

import os

nbytes = sum(d.stat().st_size for d in os.scandir('.') if d.is_file())

2018 年更新

如果您使用 Python 3.4 或更低版本,那么您可以考虑使用第三方提供的更高效的 walk 方法 scandir 包.在 Python 3.5 及更高版本中,此包已合并到标准库中,并且 os.walk 获得了相应的性能提升.

If you use Python 3.4 or previous then you may consider using the more efficient walk method provided by the third-party scandir package. In Python 3.5 and later, this package has been incorporated into the standard library and os.walk has received the corresponding increase in performance.

2019 年更新

最近我越来越多地使用pathlib,这里有一个pathlib 解决方案:

Recently I've been using pathlib more and more, here's a pathlib solution:

from pathlib import Path

root_directory = Path('.')
sum(f.stat().st_size for f in root_directory.glob('**/*') if f.is_file())

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

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