Skip to content

Instantly share code, notes, and snippets.

@cbwar
Last active January 9, 2024 09:09
Show Gist options
  • Save cbwar/d2dfbc19b140bd599daccbe0fe925597 to your computer and use it in GitHub Desktop.
Save cbwar/d2dfbc19b140bd599daccbe0fe925597 to your computer and use it in GitHub Desktop.
Python: Human readable file size
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)
@eirture
Copy link

eirture commented Jan 25, 2018

Thanks!

@pugo
Copy link

pugo commented Feb 22, 2019

I prefer a non looping solution, with something like:

def sizeof_fmt(num, suffix='B'):
    magnitude = int(math.floor(math.log(num, 1024)))
    val = num / math.pow(1024, magnitude)
    if magnitude > 7:
        return '{:.1f}{}{}'.format(val, 'Yi', suffix)
    return '{:3.1f}{}{}'.format(val, ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi'][magnitude], suffix)

@hottabxp
Copy link

Спасибо(Thanks)!

@aphor
Copy link

aphor commented Nov 30, 2020

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