Converting Bytes to a Human Readable Format with Python

{0 Comments}

I often find myself working with large numbers (in bytes) and needing to convert that down to something more humanly readable such as Terabytes, Gigabytes, Megabytes, etc.  I posted an example on a previous blog I ran, but of course my friend/co-worker Clay had to one-up me and make a better example.  Regardless, the following function is useful for converting large numbers down to something more readable:

SYMBOLS = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
PREFIX = {}

for i, s in enumerate(SYMBOLS):
PREFIX[s] = 1 << (i+1)*10

def convert_bytes(n):
for s in reversed(SYMBOLS):
if n >= PREFIX[s]:
value = float(n) / PREFIX[s]
return '%.1f%s' % (value, s)

# n is less than 1024B
return '%.1fB' % n

Example:

>>> print convert_bytes(9898989898879000000000000)
8.2Y

>>> print convert_bytes(9898989898879000000000)
8.4Z

>>> print convert_bytes(9898989898879000000)
8.6E

>>> print convert_bytes(9898989898879000)
8.8P

>>> print convert_bytes(9898989898879)
9.0T

>>> print convert_bytes(5129898234)
4.8G

>>> print convert_bytes(12898234)
12.3M

>>> print convert_bytes(24)
24.0B

Leave a Comment