[파이썬] shutil `shutil.disk_usage()`: 디스크 사용량 확인하기

In this blog post, we will explore the shutil.disk_usage() function in Python’s shutil module, which allows us to check the disk usage of a given path or directory.

Introduction to shutil.disk_usage()

The shutil.disk_usage() function is a part of the shutil module, which provides a high-level interface for various file operations in Python. It was introduced in Python 3.3 and allows us to obtain disk usage statistics for a path or directory.

Syntax

The syntax to use shutil.disk_usage() is as follows:

import shutil

disk_usage = shutil.disk_usage(path)

The function takes a path parameter, which should be a string representing a path to a directory or file. It returns a named tuple with the following attributes:

Example Usage

Let’s see an example of how to use shutil.disk_usage() to retrieve disk usage information:

import shutil

path = '/path/to/directory'
disk_usage = shutil.disk_usage(path)

print(f"Total disk space: {disk_usage.total} bytes")
print(f"Used disk space: {disk_usage.used} bytes")
print(f"Free disk space: {disk_usage.free} bytes")

In this example, we import the shutil module and specify the path variable to the desired directory or path for which we want to retrieve the disk usage information. We then call shutil.disk_usage() with the path variable as the argument and store the returned named tuple in the disk_usage variable.

Finally, we print the total, used, and free disk space by accessing the corresponding attributes of the disk_usage named tuple.

Conclusion

The shutil.disk_usage() function in Python’s shutil module is a useful tool for retrieving disk usage information. It allows developers to obtain insights about the disk space utilization of a given directory or file. By using this function, you can make more informed decisions regarding disk management and resource allocation in your Python projects.

Remember to import the shutil module before using the shutil.disk_usage() function, and provide a valid path parameter representing the directory or file you want to check the disk usage for.

I hope this blog post has provided you with a better understanding of how to use shutil.disk_usage() in Python. Happy coding!