gpt4 book ai didi

python - 获取文件的实际磁盘空间

转载 作者:太空狗 更新时间:2023-10-29 17:15:24 26 4
gpt4 key购买 nike

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

最佳答案

仅限 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

关于python - 获取文件的实际磁盘空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4274899/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com