Advertisement
Guest User

Untitled

a guest
Nov 4th, 2011
320
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.96 KB | None | 0 0
  1. SUFFIXES = {1000: ['KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
  2.             1024: ['KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB']}
  3.  
  4. def approximate_size(size, a_kilobyte_is_1024_bytes=True):
  5.     '''Convert a file size to human-readable form.
  6.  
  7.    Keyword arguments:
  8.    size -- file size in bytes
  9.    a_kilobyte_is_1024_bytes -- if True (default), use miltiples of 1024
  10.                                if False, use mutliples of 1000
  11.  
  12.    Returns: string
  13.  
  14.    '''
  15.     if size < 0:
  16.         raise ValueError('number must be non-negative')
  17.  
  18.     multiple = 1024 if a_kilobyte_is_1024_bytes else 1000
  19.  
  20.     for suffix in SUFFIXES[multiple]:
  21.         size /= multiple
  22.         if size < multiple:
  23.             return '{0:.1f} {1}'.format(size,suffix)
  24.  
  25.     raise ValueError('number too large')
  26.  
  27. if __name__ == '__main__':
  28.     print(approximate_size(1000000000000, False))
  29.     print (approximate_size(1000000000000))
  30.  
  31. raw_input('Press Enter to exit')
  32.  
  33.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement