Skip to content

Instantly share code, notes, and snippets.

@toast254
Last active May 16, 2019 14:02
Show Gist options
  • Save toast254/9c3449e0ce98440faf829e7d9c20a686 to your computer and use it in GitHub Desktop.
Save toast254/9c3449e0ce98440faf829e7d9c20a686 to your computer and use it in GitHub Desktop.
# -*- coding: utf-8 -*-
def pretty_print_file_size(file_size: int, use_base_2: bool = True, approximate: bool = True, suffix: str = 'B'):
"""
Output a file size as a human friendly str.
:param file_size: file size in bits to pretty print
:param use_base_2: choose between base 10 (False) or base 2 (True, default) divider
:param approximate: drop the float part of the result (True, default)
:param suffix: file size suffix 'o' for `octets`, 'B' for `Bytes` (default)
:return: human friendly file size as a str
"""
# https://en.wikipedia.org/wiki/File_size
units = ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z']
if use_base_2:
units = ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']
# loop over known file size prefixes
for unit in units:
# if current size is in this range
if use_base_2 and abs(file_size) < 1024.0\
or abs(file_size) < 1000.0:
# return current prefix
return str(file_size) + unit + suffix
# divide the file size to get in the next range
if use_base_2:
file_size /= 1024.0
else:
file_size /= 1000.0
# drop float part if needed
if approximate:
file_size = int(file_size)
# return the higher prefix we now atm.
if use_base_2:
return str(file_size) + 'Yi' + suffix
return str(file_size) + 'Y' + suffix
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment