formatting number of bytes to human readable format

rkmr.em at gmail.com rkmr.em at gmail.com
Wed Aug 13 00:12:26 EDT 2008


On Tue, Aug 12, 2008 at 7:31 PM, Rob Weir <rweir at ertius.org> wrote:

> On 13 Aug 2008, rkmr wrote:
> > is there any library /  function that prints number of bytes in human
> > readable format?
> > for example
> >
> > a=XX(1048576)
> > print a
> >
> > should output
> > 1 MB
>
> http://mail.python.org/pipermail/python-list/1999-December/018519.html
> is a good start - just need to change the table to something like::


hi rob,
thanks a lot!
this is what i came up with

_abbrevs = [
    (1<<50L, ' PB'),
    (1<<40L, ' TB'),
    (1<<30L, ' GB'),
    (1<<20L, ' MB'),
    (1<<10L, ' kB'),
    (1, ' bytes')
    ]

def bytestr(size, precision=1):
    """Return a string representing the greek/metric suffix of a size"""
    if size==1:
        return '1 byte'
    for factor, suffix in _abbrevs:
        if size >= factor:
            break

    float_string_split = `size/float(factor)`.split('.')
    integer_part = float_string_split[0]
    decimal_part = float_string_split[1]
    if int(decimal_part[0:precision]):
        float_string = '.'.join([integer_part, decimal_part[0:precision]])
    else:
        float_string = integer_part
    return float_string + suffix


>>> bytestr(1)
'1 byte'
>>> bytestr(1024)
'1 kB'
>>> bytestr(1024*123)
'123 kB'
>>> bytestr(1024*12342)
'12 MB'
>>> bytestr(1024*12342,2)
'12.05 MB'
>>> bytestr(1024*1234,2)
'1.20 MB'
>>> bytestr(1024*1234*1111,2)
'1.30 GB'
>>> bytestr(1024*1234*1111,1)
'1.3 GB'
>>>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20080812/22d5c0fa/attachment-0001.html>


More information about the Python-list mailing list