Best Practice to Python Calculate Disk Free Space for Beginners – Python Tutorial

By | September 3, 2019

When we are downloading files to local disk using python, we should detect the free space of disk. If there is no enough space, you should stop downloading. In this tutorial, we will write an function to calculate disk free space by python.

python calculate disk free space

You should notice, to calculate disk free space, python uses different methods to calculate based on different system operation.

Import libraries

import sys
import io
import os
import ctypes
import platform

Format disk free size

def formatSize(bytes):
    try:
        bytes = float(bytes)
        kb = bytes / 1024
    except:
        return "Error"

    if kb >= 1024:
        M = kb / 1024
        if M >= 1024:
            G = M / 1024
            return "%.2fG" % (G)
        else:
            return "%.2fM" % (M)
    else:
        return "%.2fkb" % (kb)

Calculate disk free space based on system operation

def getDiskFreeSpace(disk):
    """ Return disk free space (in bytes)
    """
    if platform.system() == 'Windows':
        free_bytes = ctypes.c_ulonglong(0)
        ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(disk), None, None, ctypes.pointer(free_bytes))
        return formatSize(free_bytes.value)
    else:
        st = os.statvfs(disk)
        return formatSize(st.f_bavail * st.f_frsize)

There is an example to show how to use.

print(getDiskFreeSpace("F:\\"))

The free space is: 14.82G

 

Leave a Reply