如何在 python 中获取磁盘上的实际文件大小? (它在硬盘驱动器上占用的实际大小)。
原文由 Alex 发布,翻译遵循 CC BY-SA 4.0 许可协议
如何在 python 中获取磁盘上的实际文件大小? (它在硬盘驱动器上占用的实际大小)。
原文由 Alex 发布,翻译遵循 CC BY-SA 4.0 许可协议
仅限 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 许可协议
2 回答5.1k 阅读✓ 已解决
2 回答1.1k 阅读✓ 已解决
4 回答1k 阅读✓ 已解决
3 回答1.1k 阅读✓ 已解决
3 回答1.2k 阅读✓ 已解决
1 回答1.7k 阅读✓ 已解决
1 回答1.2k 阅读✓ 已解决