Add: utli func for converting bytes to human readable formats

This commit is contained in:
Aroy-Art 2024-04-29 21:03:15 +02:00
parent 22f841280c
commit cc104c1292
Signed by: Aroy
GPG key ID: DB9689E9391DD156

View file

@ -1,6 +1,5 @@
import math, re
import re
def get_urls(string:str = None) -> list: def get_urls(string:str = None) -> list:
""" """
@ -19,3 +18,20 @@ def get_urls(string:str = None) -> list:
return [x[0] for x in re.findall(regex, string)] return [x[0] for x in re.findall(regex, string)]
def convert_size(size_bytes: int) -> str:
"""
A function that converts the given size in bytes to a human-readable format.
Parameters:
size_bytes (int): An integer representing the size in bytes to be converted.
Returns:
A string representing the converted size with the appropriate unit (B, KiB, MiB, GiB, etc.).
"""
if size_bytes == 0:
return "0B"
size_name = ("B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB")
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]}"