EvilZone
Programming and Scripting => Scripting Languages => : Kulverstukas October 22, 2012, 07:13:50 PM
-
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:
print calculateSize(104857606)
will produce:
C:\>python test.py
100.00 mB
-
Nice snippet. Using this snippet in combination with os.path.getsize(filepath) will get you a better filesize output.
-
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.
-
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
-
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:
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...