Created
January 18, 2025 06:11
-
-
Save nathan-cruz77/c96e8e647c84aef1273ccd333b1d7456 to your computer and use it in GitHub Desktop.
Bytes to human-readable format
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
# 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