Reputation: 11932
How can we display a human readable byte size in python?
We need to convert large unreadable int
results, like the ones from os.stat(r'C:\1.pdf').st_size
(Answering my own question below with f-strings for python versions above 3.6, please add your own answers if they apply to other python versions or other ways of formatting)
Upvotes: 1
Views: 1632
Reputation: 11932
Just wanted to share this little snippet in case anyone finds it usefeul, this function converts byte-sizes (like the ones you'd get from os.stat(r'C:\1.pdf').st_size
)
from typing import Union
def readable_size(size: Union[int, float, str]) -> str:
units = ('KB', 'MB', 'GB', 'TB')
size_list = [f'{int(size):,} B'] + [f'{int(size) / 1024 ** (i + 1):,.1f*} {u}' for i, u in enumerate(units)]
return [size for size in size_list if not size.startswith('0.')][-1]
If you don't want to do from typing import Union
just remove that type-hint from the function, this is here just to show that this function can accept int
, float
, and str
arguments. A stripped down version would look like this:
def readable_size(size):
units = ('KB', 'MB', 'GB', 'TB')
size_list = [f'{int(size):,} B'] + [f'{int(size) / 1024 ** (i + 1):,.1f*} {u}' for i, u in enumerate(units)]
return [size for size in size_list if not size.startswith('0.')][-1]
Examples:
>>> import random
>>> for i in range(15):
... size = random.randint(1 ** i, 9 ** i)
... print(f'{size} = {readable_size(size)}')
...
1 = 1 B
3 = 3 B
61 = 61 B
267 = 267 B
5127 = 5.0 KB
37700 = 36.8 KB
68512 = 66.9 KB
342383 = 334.4 KB
42580724 = 40.6 MB
40250452 = 38.4 MB
1789601996 = 1.7 GB
16242182039 = 15.1 GB
131167506597 = 122.2 GB
1827741623713 = 1.7 TB
5613973017836 = 5.1 TB
Limitations: this function only lists units up to terabytes (TB), but that can easily be modified by extending the units
tuple. Obviously this uses f-strings so only applies for python versions above 3.6
Upvotes: 5