How to Check Disk Free Space in Python with shutil.disk_usage

This Python script uses the standard library shutil.disk_usage to report total, used, and free disk space in bytes, plus a percentage usage figure.

Easy Python 3.9+ Aug 9, 2026 Files & data 15 views 0 copies

Python code

15 lines
Python 3.9+
import shutil


def check_disk_free_space(path="/"):
    """Return a tuple of total, used, and free disk space in bytes."""
    usage = shutil.disk_usage(path)
    return usage.total, usage.used, usage.free


if __name__ == "__main__":
    total, used, free = check_disk_free_space()
    print(f"Total: {total:,} bytes")
    print(f"Used: {used:,} bytes")
    print(f"Free: {free:,} bytes")
    print(f"Usage: {used / total * 100:.1f}%")

Output

stdout
Total: 1,000,202,024,448 bytes
Used: 512,100,233,216 bytes
Free: 488,101,791,232 bytes
Usage: 51.2%

How it works

The shutil.disk_usage function returns a named tuple with total, used, and free attributes representing disk space in bytes. Since it is part of the standard library, no third-party packages are needed. The example formats the raw byte counts with thousands separators and calculates the used percentage by dividing used by total and multiplying by 100. The function accepts a path argument, defaulting to / (root directory), so it works on any mounted filesystem you provide a path for.

Common mistakes

  • Passing a file path instead of a directory path—make sure the path points to a filesystem mount point or existing directory.
  • Forgetting that the values are bytes and not gigabytes, leading to misinterpretation of the output.
  • Not handling PermissionError when checking paths without read/execute access on some systems.

Variations

  1. Convert bytes to human-readable units like GB by dividing by 1024**3.
  2. Check multiple mount points by looping over a list of directories with `shutil.disk_usage(path)` in a for loop.

Real-world use cases

  • Monitoring disk usage in a cron job to alert when a server's free space drops below a safety threshold.
  • Validating available storage before downloading large files or running database backups in a pipeline.
  • Creating a system health dashboard that reports per-mount disk usage across cloud instances.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Files & data

Related tutorials and quizzes for this topic.