EvilZone

Programming and Scripting => Scripting Languages => : Kulverstukas October 22, 2012, 07:13:50 PM

: [Python] calculate content size from bytes to something else
: Kulverstukas October 22, 2012, 07:13:50 PM
: (python)
def calculateSize(self, bytes):
    abbrevs = ["kB", "mB", "gB"]
    if (bytes == None):
        size = "0 kB"
    else:
        bytes = float(bytes)
        for abbrev in abbrevs:
            if (bytes > 1024.0):
                bytes = bytes / 1024.0
                size = "%.2f %s" % (bytes, abbrev)
    return size

This is a simple script. It will divide the given bytes by 1024 until they are not more than 1024 or the last abbreviation is reached. To keep track of the current data size, a abbreviation is added at the end. If you want to add more of those, put them in the "abbrevs" list.

Example usage:
: (python)
print calculateSize(104857606)
will produce:
:
C:\>python test.py
100.00 mB
: Re: [Python] calculate content size from bytes to something else
: Deque October 22, 2012, 08:11:38 PM
Nice snippet. Using this snippet in combination with os.path.getsize(filepath) will get you a better filesize output.
: Re: [Python] calculate content size from bytes to something else
: s3my0n October 23, 2012, 01:22:50 AM
Nice snippet. Using this snippet in combination with os.path.getsize(filepath) will get you a better filesize output.

You can also do "ls -lh" to give a better file size output. You can even do this to make your life easier: "alias ll="ls -lh " . Then you can just use "ll" to view files with human readable file sizes.
: Re: [Python] calculate content size from bytes to something else
: Kulverstukas October 23, 2012, 09:12:52 AM
You can also do "ls -lh" to give a better file size output. You can even do this to make your life easier: "alias ll="ls -lh " . Then you can just use "ll" to view files with human readable file sizes.
But that's not python anymore :P
: Re: [Python] calculate content size from bytes to something else
: madara June 18, 2013, 12:12:12 PM
: (python)
def calculateSize(self, bytes):
    abbrevs = ["kB", "mB", "gB"]
    if (bytes == None):
        size = "0 kB"
    else:
        bytes = float(bytes)
        for abbrev in abbrevs:
            if (bytes > 1024.0):
                bytes = bytes / 1024.0
                size = "%.2f %s" % (bytes, abbrev)
    return size



ok can be good, but now we can rewrite it in python:


: (python)

import math
def byteszConverter(bytes=1):
    abbrevs = ['bytes', 'kb', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
    esp = math.floor(math.log(bytes)/math.log(1024))
    return '{0:.2f}'.format(bytes/math.pow(1024, esp)) + ' ' + abbrevs[esp]
Python 2.x users  need simple changes...