获取文件实际磁盘空间
我怎么在Python中获取文件在硬盘上实际占用的大小?(就是它在硬盘上真正占用的空间大小)。
7 个回答
7
这里是获取文件在磁盘上大小的正确方法,适用于那些设置了 st_blocks
的平台:
import os
def size_on_disk(path):
st = os.stat(path)
return st.st_blocks * 512
其他一些答案提到要用 os.stat(path).st_blksize
或 os.vfsstat(path).f_bsize
来乘以某个值,这些说法都是错误的。
Python 文档中关于 os.stat_result.st_blocks
的说明非常清楚:
st_blocks
为文件分配的 512 字节块的数量。如果文件有空洞,这个值可能会小于st_size
/512。
此外,stat(2)
手册页 也说了同样的事情:
blkcnt_t st_blocks; /* Number of 512B blocks allocated */
18
仅适用于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
2
st = os.stat(…)
du = st.st_blocks * st.st_blksize
当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。