Python format size application (converting B to KB, MB, GB, TB) Python format size application (converting B to KB, MB, GB, TB) python python

Python format size application (converting B to KB, MB, GB, TB)


Fixed version of Bryan_Rch's answer:

def format_bytes(size):    # 2**10 = 1024    power = 2**10    n = 0    power_labels = {0 : '', 1: 'kilo', 2: 'mega', 3: 'giga', 4: 'tera'}    while size > power:        size /= power        n += 1    return size, power_labels[n]+'bytes'


def humanbytes(B):   'Return the given bytes as a human friendly KB, MB, GB, or TB string'   B = float(B)   KB = float(1024)   MB = float(KB ** 2) # 1,048,576   GB = float(KB ** 3) # 1,073,741,824   TB = float(KB ** 4) # 1,099,511,627,776   if B < KB:      return '{0} {1}'.format(B,'Bytes' if 0 == B > 1 else 'Byte')   elif KB <= B < MB:      return '{0:.2f} KB'.format(B/KB)   elif MB <= B < GB:      return '{0:.2f} MB'.format(B/MB)   elif GB <= B < TB:      return '{0:.2f} GB'.format(B/GB)   elif TB <= B:      return '{0:.2f} TB'.format(B/TB)tests = [1, 1024, 500000, 1048576, 50000000, 1073741824, 5000000000, 1099511627776, 5000000000000]for t in tests: print '{0} == {1}'.format(t,humanbytes(t))

Output:

1 == 1.0 Byte1024 == 1.00 KB500000 == 488.28 KB1048576 == 1.00 MB50000000 == 47.68 MB1073741824 == 1.00 GB5000000000 == 4.66 GB1099511627776 == 1.00 TB5000000000000 == 4.55 TB

and for future me here it is in Perl too:

sub humanbytes {   my $B = shift;   my $KB = 1024;   my $MB = $KB ** 2; # 1,048,576   my $GB = $KB ** 3; # 1,073,741,824   my $TB = $KB ** 4; # 1,099,511,627,776   if ($B < $KB) {      return "$B " . (($B == 0 || $B > 1) ? 'Bytes' : 'Byte');   } elsif ($B >= $KB && $B < $MB) {      return sprintf('%0.02f',$B/$KB) . ' KB';   } elsif ($B >= $MB && $B < $GB) {      return sprintf('%0.02f',$B/$MB) . ' MB';   } elsif ($B >= $GB && $B < $TB) {      return sprintf('%0.02f',$B/$GB) . ' GB';   } elsif ($B >= $TB) {      return sprintf('%0.02f',$B/$TB) . ' TB';   }}


good idea for me:

def convert_bytes(num):    """    this function will convert bytes to MB.... GB... etc    """    step_unit = 1000.0 #1024 bad the size    for x in ['bytes', 'KB', 'MB', 'GB', 'TB']:        if num < step_unit:            return "%3.1f %s" % (num, x)        num /= step_unit