Home ยป Python Program to Get the Disk Usage and save in a CSV File

Python Program to Get the Disk Usage and save in a CSV File

In this article we will look at 2 methods to get the disk usage and then save it to a csv file

Using the WMI Module

We can use the WMI module to fetch the disk’s name, the total size of that disk, and the amount of free space it has (both in bytes).

Install the WMI module using the following command:

pip install WMI

 

import wmi
import pandas as pd
 
key = wmi.WMI()
drive_name = []
free_space = []
total_size = []
 
for drive in key.Win32_LogicalDisk():
    drive_name.append(drive.Caption)
    free_space.append(round(int(drive.FreeSpace)/1e+9, 2))
    total_size.append(round(int(drive.Size)/1e+9, 2))
    print("================")
    print("Drive Name :", drive.Caption+"\n================",
          "\nFree Space Available in GB : \n", round(
              int(drive.FreeSpace)/1e+9, 2),
          "\nTotal Size in GB :\n", round(int(drive.Size)/1e+9, 2))
 
size_dict = {'Directory Name': drive_name,
             'Free Space (in GB)': free_space,
             'Total Size (in GB)': total_size}
 
data_frame = pd.DataFrame(size_dict)
data_frame.to_csv("disk_usage.csv")

 

Using the psutil Module

We can generate a disk usage report in a CSV file using Python by using the psutil library. This library provides a wide variety of functions for retrieving system information.

To use the psutil library, you need to first install it using pip install psutil.

After that, you can use the disk_usage function to retrieve the total size, used space, and free space of a given path.

import psutil
import pandas as pd
 
# Path to the drive
drive = "C:\\"
 
# Get the disk usage statistics
stats = psutil.disk_usage(drive)
 
total_size = stats.total / 1024**3  # Convert bytes to GB
used_space = stats.used / 1024**3
free_space = stats.free / 1024**3
 
# Create a dictionary with the disk usage data
data = {'Directory Name': drive, 'Total Size (in GB)': total_size,
        'Used Space (in GB)': used_space, 'Free Space (in GB)': free_space}
 
import pandas as pd
 
# Create a Pandas DataFrame with an index
df = pd.DataFrame(data, index=[0])
 
# Write the DataFrame to a CSV file
df.to_csv("disk_usage1.csv", index=False)
 
# Print disk usage statistics
print("Disk usage statistics:")
print("Total Size : ", total_size,
      "Free Space Available : ", free_space,
      "Used_Space : ", used_space)

 

You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More