<div dir="ltr">On Tue, Aug 12, 2008 at 7:31 PM, Rob Weir <span dir="ltr"><<a href="mailto:rweir@ertius.org">rweir@ertius.org</a>></span> wrote:<br><div class="gmail_quote"><blockquote class="gmail_quote" style="border-left: 1px solid rgb(204, 204, 204); margin: 0pt 0pt 0pt 0.8ex; padding-left: 1ex;">
<div><div></div><div class="Wj3C7c">On 13 Aug 2008, rkmr wrote:<br>
> is there any library /  function that prints number of bytes in human<br>
> readable format?<br>
> for example<br>
><br>
> a=XX(1048576)<br>
> print a<br>
><br>
> should output<br>
> 1 MB<br>
<br>
</div></div><a href="http://mail.python.org/pipermail/python-list/1999-December/018519.html" target="_blank">http://mail.python.org/pipermail/python-list/1999-December/018519.html</a><br>
is a good start - just need to change the table to something like::</blockquote><div><br>hi rob,<br>thanks a lot!<br>this is what i came up with<br><br>_abbrevs = [<br>    (1<<50L, ' PB'),<br>    (1<<40L, ' TB'),<br>
    (1<<30L, ' GB'),<br>    (1<<20L, ' MB'),<br>    (1<<10L, ' kB'),<br>    (1, ' bytes')<br>    ]<br><br>def bytestr(size, precision=1):<br>    """Return a string representing the greek/metric suffix of a size"""<br>
    if size==1:<br>        return '1 byte'<br>    for factor, suffix in _abbrevs:<br>        if size >= factor:<br>            break<br><br>    float_string_split = `size/float(factor)`.split('.')<br>    integer_part = float_string_split[0]<br>
    decimal_part = float_string_split[1]<br>    if int(decimal_part[0:precision]):<br>        float_string = '.'.join([integer_part, decimal_part[0:precision]])<br>    else:<br>        float_string = integer_part<br>
    return float_string + suffix<br> <br><br>>>> bytestr(1)<br>'1 byte'<br>>>> bytestr(1024)<br>'1 kB'<br>>>> bytestr(1024*123)<br>'123 kB'<br>>>> bytestr(1024*12342)<br>
'12 MB'<br>>>> bytestr(1024*12342,2)<br>'12.05 MB'<br>>>> bytestr(1024*1234,2)<br>'1.20 MB'<br>>>> bytestr(1024*1234*1111,2)<br>'1.30 GB'<br>>>> bytestr(1024*1234*1111,1)<br>
'1.3 GB'<br>>>><br><br><br><br></div></div><br></div>