Skip to content

Instantly share code, notes, and snippets.

@afparsons
Created August 19, 2022 19:18
Show Gist options
  • Save afparsons/297bff563b6c18285d38a6d5d9abb175 to your computer and use it in GitHub Desktop.
Save afparsons/297bff563b6c18285d38a6d5d9abb175 to your computer and use it in GitHub Desktop.
Convert size in bytes to human-readable amount
"""
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