在OS/X上的python中查找可用磁盘空间

Eve*_*ert 25 python diskspace

我正在寻找我的HD上的空闲字节数,但是在python上这样做很麻烦.

我尝试过以下方法:

import os

stat = os.statvfs(path)
print stat.f_bsize * stat.f_bavail
Run Code Online (Sandbox Code Playgroud)

但是,在OS/X上它给了我一个17529020874752字节,大约是1.6 TB,这将是非常好的,但不幸的是不是真的.

达到这个数字的最佳方法是什么?

Nic*_*ley 38

尝试使用f_frsize而不是f_bsize.

>>> s = os.statvfs('/')
>>> (s.f_bavail * s.f_frsize) / 1024
23836592L
>>> os.system('df -k /')
Filesystem   1024-blocks     Used Available Capacity  Mounted on
/dev/disk0s2   116884912 92792320  23836592    80%    /
Run Code Online (Sandbox Code Playgroud)

  • 不,不是.`statvfs`*module*在Python 3.x中被弃用/消失了(这是将statvfs输出作为元组查找的索引与对象的属性公开的旧方法),但我在答案中没有使用该模块.但是,`os.statvfs`并未弃用 - 实际上它甚至收到了3.6中的更新:https://docs.python.org/3.6/library/os.html#os.statvfs.对现代Python进行调整所需的唯一改变是使用整数除法(`//`),尽管`shutil.disk_usage`在另一个答案中肯定是一个更容易的选择! (3认同)

Gia*_*olà 19

在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)
Run Code Online (Sandbox Code Playgroud)

用法:

>>> disk_usage('/')
usage(total=21378641920, used=7650934784, free=12641718272)
>>>
Run Code Online (Sandbox Code Playgroud)

对于Windows,您可以使用psutil.


ram*_*daz 10

在python 3.3及更高版本中,shutil为您提供了相同的功能

>>> import shutil
>>> shutil.disk_usage("/")
usage(total=488008343552, used=202575314944, free=260620050432)
>>> 
Run Code Online (Sandbox Code Playgroud)