Last active
May 16, 2019 14:02
-
-
Save toast254/9c3449e0ce98440faf829e7d9c20a686 to your computer and use it in GitHub Desktop.
This file contains 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
# -*- 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