sizes.py
Program to represent bytes in apropriate format.
Size 2.3 kB - File type text/python-sourceFile contents
#!/usr/bin/python
"""USAGE:sizes
Test formatBytes
GPL Licence.
copyright Bauer Data ApS.
"""
#
# see http://en.wikipedia.org/wiki/Bytes
radix ={
"b" :1, # bytes
"kb":1024, # Kilobyte
"mb":1024**2, # Megabyte
"gb":1024**3, # Gigabyte
"tb":1024**4, # Terabyte
"pb":1024**5, # Petabyte
"eb":1024**6, # Exabyte
"zb":1024**7, # Zettabyte
"yb":1024**8, # Yottabyte
}
def formatBytes(value, suffix="b", decimals=1):
"""convert value with suffix to nice representation
value : is number to konvert
suffix : is valuer of values
decimals : is precission in output
Examples
formatBytes(1232345789452) --> "1.1 tb"
formatBytes(1232345789452,"mb") --> "1.1 eb"
formatBytes(1232345789452,decimals=3) --> "1.121 tb"
"""
# try to convert to nicest representation
value *= float( radix[ suffix ] )
if value < 1.0 :
# fraction off bytes no possible
return "0 b"
# set prefferred format according to parameter decimals
format="%%.%sf %%s" % (decimals)
# if bytes larger then higest suffix safe the best fit value in less_res
less_res=value
for (suffix, faktor) in radix.items():
res = value/faktor
if 1.0 <= res < 1024:
if suffix=='b':
# bytes dont come in float.
format = "%s %s"
res = int(res)
return format % ( res, suffix )
if less_res > res:
less_res = res
less_suffix=suffix
else:
# out off range use higst suffix to konvert :-)
return format % ( less_res, less_suffix )
if __name__ == "__main__":
print 'formatBytes(1232345789452)',
print formatBytes(1232345789452)
print 'formatBytes(1232345789452,"mb")',
print formatBytes(1232345789452,"mb")
print 'formatBytes(1232345789452,decimals=3)',
print formatBytes(1232345789452,decimals=3)
print formatBytes(0.664) # wrong fractions off bytes not possible
print formatBytes(0.664,suffix="kb", decimals=3 )
for suffix in radix.keys():
for bytes in range (1024, 3000, 1300):
print "formatBytes(%d,suffix=%s)\t= " % (bytes,suffix),
print formatBytes(bytes,suffix=suffix)
Click here to get the file