获取文件的实际磁盘空间

新手上路,请多包涵

如何在 python 中获取磁盘上的实际文件大小? (它在硬盘驱动器上占用的实际大小)。

原文由 Alex 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 752
2 个回答
st = os.stat(…)
du = st.st_blocks * st.st_blksize

原文由 ephemient 发布,翻译遵循 CC BY-SA 2.5 许可协议

仅限 UNIX:

 import os
from collections import namedtuple

_ntuple_diskusage = namedtuple('usage', 'total used free')

def disk_usage(path):
    """Return disk usage statistics about the given path.

    Returned valus is a named tuple with attributes 'total', 'used' and
    'free', which are the amount of total, used and free space, in bytes.
    """
    st = os.statvfs(path)
    free = st.f_bavail * st.f_frsize
    total = st.f_blocks * st.f_frsize
    used = (st.f_blocks - st.f_bfree) * st.f_frsize
    return _ntuple_diskusage(total, used, free)

用法:

 >>> disk_usage('/')
usage(total=21378641920, used=7650934784, free=12641718272)
>>>

编辑 1 - 也适用于 Windows: https ://code.activestate.com/recipes/577972-disk-usage/?in=user-4178764

编辑 2 - 这在 Python 3.3+ 中也可用: https ://docs.python.org/3/library/shutil.html#shutil.disk_usage

原文由 Giampaolo Rodolà 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题