Created
August 19, 2022 19:18
-
-
Save afparsons/297bff563b6c18285d38a6d5d9abb175 to your computer and use it in GitHub Desktop.
Convert size in bytes to human-readable amount
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Adpated from: https://stackoverflow.com/a/14822210/4189676 | |
""" | |
from math import floor, log | |
def bytes_to_human_readable(number_of_bytes: int) -> str: | |
magnitude: int = int(floor(log(number_of_bytes, 1024))) | |
value: float = number_of_bytes / pow(1024, magnitude) | |
if magnitude > 3: | |
return f'{value:.1f} TiB' | |
return '{:3.2f} {}B'.format(value, ('', 'Ki', 'Mi', 'Gi')[magnitude]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment