Python psutil – Get system disk usage

In this post we will be creating a Python script that will get the usage of system disks on the local machine. This is achieved using ‘psutil’ which is a library for retrieving information on running processes and system utilization.

To install the library run the following command.

pip install psutil

See the snippet of Python code below which get the system disk usage for the local machine. We start by retrieving the list of disk partitions, we then print usage information for each of the partitions.

In this example the total, used, free and usage percentage of memory for each disk is retrieved.

import psutil

partitions = psutil.disk_partitions()

for partition in partitions:
    usage = psutil.disk_usage(partition.mountpoint)
    print(f'Device: {partition.device}')
    print(f'Mountpoint: {partition.mountpoint}')
    print(f'Total: {**3:.2f} GB')
    print(f'Used: {usage.used/1024**3:.2f} GB')
    print(f'Free: {**3:.2f} GB')
    print(f'Percentage: {usage.percent}%')

An example of output can be seen below.

Device: C:\
Mountpoint: C:\
Total: 237.28 GB
Used: 143.48 GB
Free: 93.80 GB
Percentage: 60.5%

Take a look at some of our other content around the Python programming language by clicking here.

Leave a Reply