Skip to content

Instantly share code, notes, and snippets.

@nathan-cruz77
Created January 18, 2025 06:11
Show Gist options
  • Save nathan-cruz77/c96e8e647c84aef1273ccd333b1d7456 to your computer and use it in GitHub Desktop.
Save nathan-cruz77/c96e8e647c84aef1273ccd333b1d7456 to your computer and use it in GitHub Desktop.
Bytes to human-readable format
# Formats `n` bytes into human representation.
#
# Sample usage:
#
# >>> human_size(10)
# '10 B'
#
# >>> human_size(1_048)
# '1 KB'
#
# >>> human_size(10_000_000)
# '9 MB'
#
# >>> human_size(10_000_000_000)
# '9 GB'
#
def human_size(n, units=('B','KB','MB','GB','TB', 'PB', 'EB')):
n = int(n)
if n < 1024:
return f'{n} {units[0]}'
return human_size(n >> 10, units[1:])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment