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

前端 未结 15 1666
轮回少年
轮回少年 2021-02-01 16:13

I am trying to write an application to convert bytes to kb to mb to gb to tb. Here\'s what I have so far:

def size_format(b):
    if b < 1000:
              r         


        
15条回答
  •  滥情空心
    2021-02-01 16:36

    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 Byte
    1024 == 1.00 KB
    500000 == 488.28 KB
    1048576 == 1.00 MB
    50000000 == 47.68 MB
    1073741824 == 1.00 GB
    5000000000 == 4.66 GB
    1099511627776 == 1.00 TB
    5000000000000 == 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';
       }
    }
    

提交回复
热议问题