Skip to content

Instantly share code, notes, and snippets.

@tomwhoiscontrary
Forked from varjmes/humansize.py
Last active August 29, 2015 14:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomwhoiscontrary/d3f56289651c6cac43ec to your computer and use it in GitHub Desktop.
Save tomwhoiscontrary/d3f56289651c6cac43ec to your computer and use it in GitHub Desktop.
SUFFIXES = {1000: ['KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
1024: ['KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB']}
def approximate_size(size, a_kilobyte_is_1024_bytes=True):
"""Convert a file size to human-readable form.
Keyword arguments:
size -- file size in bytes
a_kilobyte_is_1024_bytes -- if True (default), use multiples of 1024,
if False, use multiples of 1000
Returns: string
"""
if size < 0:
raise ValueError("Number must be non-negative")
multiple = 1024 if a_kilobyte_is_1024_bytes else 1000
size_of_unit = 1
for unit_suffix in SUFFIXES[multiple]:
size_of_unit *= multiple
number_of_units = float(size) / size_of_unit
if number_of_units < multiple:
return "{0:.1f} {1}".format(number_of_units, unit_suffix)
"""
Can someone tell me how the above for loop selects the correct suffix? It does it as if by magic.
I understand how everything else works, but don't understand how the right suffix within the list
is selected.
"""
raise ValueError("Number too large")
if __name__ == "__main__":
print(approximate_size(1000000000000, False))
print(approximate_size(1000000000000))
@varjmes
Copy link

varjmes commented Dec 28, 2014

a little, thanks :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment