Last active
January 9, 2024 09:09
-
-
Save cbwar/d2dfbc19b140bd599daccbe0fe925597 to your computer and use it in GitHub Desktop.
Python: Human readable file size
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
def sizeof_fmt(num, suffix='o'): | |
"""Readable file size | |
:param num: Bytes value | |
:type num: int | |
:param suffix: Unit suffix (optionnal) default = o | |
:type suffix: str | |
:rtype: str | |
""" | |
for unit in ['', 'k', 'M', 'G', 'T', 'P', 'E', 'Z']: | |
if abs(num) < 1024.0: | |
return "%3.1f %s%s" % (num, unit, suffix) | |
num /= 1024.0 | |
return "%.1f%s%s" % (num, 'Yi', suffix) |
I got tired of rewriting these little functions from scratch, now I just import my library. For maximum convenience, it works with str.format() support. It has all the sizes in NIST/IEC and SI units and conventional nonstandard units.
>>> from datasize import DataSize
>>> 'My new {:GB} SSD really only stores {:.2GiB} of data.'.format(DataSize('750GB'),DataSize(DataSize('750GB') * 0.8))
'My new 750GB SSD really only stores 558.79GiB of data.'
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Спасибо(Thanks)!