5dollarwhitebox.org - theboxownsyou

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

RSS Feed

Reply to comment

Same thing w/ base-2 constants

Anonymous (not verified) — Sat, 2009-08-01 21:51

def convert_bytes(n):
    K, M, G, T = 1 << 10, 1 << 20, 1 << 30, 1 << 40
    if   n >= T:
        return '%.1fT' % (float(n) / T)
    elif n >= G:
        return '%.1fG' % (float(n) / G)
    elif n >= M:
        return '%.1fM' % (float(n) / M)
    elif n >= K:
        return '%.1fK' % (float(n) / K)
    else:
        return '%d' % n
 
def test_bytes():
    for n in range(15):
        print '%15d %8s' % (10**n, convert_bytes(10**n))

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.