import glob
import subprocess
from prettytable import PrettyTable
from math import log # Import log from the math module
def convert_size(size_bytes):
"""Convert bytes to a human-readable format (KB, MB, GB)."""
if size_bytes == 0:
return "0 Bytes"
size_names = ["Bytes", "KB", "MB", "GB"]
i = int(log(size_bytes, 1024))
p = 1024 ** i
s = round(size_bytes / p, 2)
return f"{s} {size_names[i]}"
# Function to fetch and sort disk usage, then print a pretty table
def test(path, extension):
table = PrettyTable(field_names=["File", "Disk Usage"])
# Collect file sizes and names
usage_info = []
for file in glob.glob(f'{path}*.{extension}'):
if file:
usage = subprocess.getoutput(f'du -b "{file}"')
size, _ = usage.split() # Get size, ignore the rest
usage_info.append((file, int(size))) # Store as a tuple of (file, size)
# Sort by size (second element of the tuple)
usage_info.sort(key=lambda x: x[1], reverse=True)
# Add sorted data to the table with human-readable sizes
for file, size in usage_info:
human_readable_size = convert_size(size)
table.add_row([file, human_readable_size])
print(table)
# Get user input for directory path and file extension
path = input("Enter the directory path: ")
file_extension = input("Enter the file extension (without dot): ")
# Example usage
test(path, file_extension)
No hay comentarios:
Publicar un comentario