5dollarwhitebox.org - theboxownsyou

  • blog
  • projects
  • articles
  • tech wiki
  • about
  • login
Home › Python: Converting Bytes to Tb/Gb/Mb/Kb

RSS Feed

Reply to comment

Python: Converting Bytes to Tb/Gb/Mb/Kb

drks — Fri, 2009-06-05 20:08

Just dropping a quick entry here, so I can find it later. Maybe later on I'll elaborate more on some similar stuff.

This is just a quick example I wrote of taking bytes, and converting them to human readable sizes:

def convert_bytes(bytes):
    bytes = float(bytes)
    if bytes >= 1099511627776:
        terabytes = bytes / 1099511627776
        size = '%.2fT' % terabytes
    elif bytes >= 1073741824:
        gigabytes = bytes / 1073741824
        size = '%.2fG' % gigabytes
    elif bytes >= 1048576:
        megabytes = bytes / 1048576
        size = '%.2fM' % megabytes
    elif bytes >= 1024:
        kilobytes = bytes / 1024
        size = '%.2fK' % kilobytes
    else:
        size = '%.2fb' % bytes
    return size



Here is an example of the output:

>>> convert_bytes(9898989898879)
'9.00T'
 
>>> convert_bytes(5129898234)
'4.78G'
 
>>> convert_bytes(12898234)
'12.30M'
 
>>> convert_bytes(989898)
'966.70K'


Hoping somebody finds that useful.



‹ Python: API Key [Token] Based Authentication in TurboGears 2.1 [UPDATED] up Python: Creating a Progress Bar (Text/Console) ›
  • Printer-friendly version

Reply

The content of this field is kept private and will not be shown publicly.
Input format
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.
  • Lines and paragraphs break automatically.
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <bash>, <c>, <cpp>, <diff>, <drupal5>, <drupal6>, <java>, <javascript>, <mysql>, <perl>, <php>, <python>, <ruby>. Beside the tag style "<foo>" it is also possible to use "[foo]".

More information about formatting options



Who's online

There are currently 0 users and 1 guest online.
  • blog
  • projects
  • articles
  • tech wiki
  • about
  • login

5dollarwhitebox.org is not responsible in anyway for actions performed based on information found on this site.