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.
Python code
15 linesimport 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
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
- Convert bytes to human-readable units like GB by dividing by 1024**3.
- 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
More from Files & data
- Append a Line to a Log File in Python easy
- Audit File Permissions Across a Project in Python easy
- Automatically Detect Corrupted Files Using SHA-256 Checksums in Python easy
- Automatically Highlight Data Validation Errors Inside Excel Files in Python easy
- Build a Command-Line To-Do List Application with Data Persistence in Python easy
- Build a File Index by Relative Path Hash Map in Python easy
Keep learning
Related tutorials and quizzes for this topic.