使用 Python 计算目录的大小?
要在 Python 中计算目录的大小并将其格式化为人类可读的格式(例如 KB、MB、GB),可以使用os和humanize模块。以下解决方案可计算目录及其子目录中所有文件的大小,并将结果格式化为更易读的格式:
os
humanize
下面是实现此目的的函数:
import os def get_directory_size(path): total_size = 0 # Walk through all directories and files in the given path for dirpath, dirnames, filenames in os.walk(path): for filename in filenames: file_path = os.path.join(dirpath, filename) # Check if it is a file before getting its size if os.path.isfile(file_path): total_size += os.path.getsize(file_path) return total_size def format_size(size_bytes): # Handle zero bytes if size_bytes == 0: return "0B" # Define size units size_name = ("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB") i = int(math.floor(math.log(size_bytes, 1024))) p = math.pow(1024, i) s = round(size_bytes / p, 2) return f"{s} {size_name[i]}" # Usage example directory_path = "your_directory_path" # Replace with your directory path size_in_bytes = get_directory_size(directory_path) formatted_size = format_size(size_in_bytes) print(f"Total size of '{directory_path}' is: {formatted_size}")
get_directory_size(path)
os.walk()
os.path.getsize(file_path)
format_size(size_bytes)
如果目录为 2.34 GB,则输出将如下所示:
Total size of 'your_directory_path' is: 2.34 GB
pip install humanize
format_size
humanize.naturalsize(size_bytes)