Find free disk space in python on OS/X

后端 未结 7 1174
死守一世寂寞
死守一世寂寞 2020-12-08 07:51

I\'m looking for the number of free bytes on my HD, but have trouble doing so on python.

I\'ve tried the following:

import os

stat = os.statvfs(path         


        
7条回答
  •  生来不讨喜
    2020-12-08 08:14

    On 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)
    

    Usage:

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

    For Windows you might use psutil.

提交回复
热议问题