vidjil_utils.py 803 Bytes
Newer Older
1 2
import math

3
def format_size(n, unit='B'):
4 5
    '''
    Takes an integer n, representing a filesize and returns a string
6 7
    where the size is formatted with the correct SI prefix and
    with a constant number of significant digits.
8 9

    Example:
10 11 12 13 14 15
    >>> format_size(42)
    '42 B'
    >>> format_size(123456)
    '123 kB'
    >>> format_size(1000*1000)
    '1.00 MB'
16
    >>> format_size(1024*1024*1024)
17 18 19
    '1.07 GB'
    >>> format_size(42*(2**40))
    '46.2 TB'
20
    '''
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
    size = float(n)
    PREFIXES = ['', 'k', 'M', 'G', 'T', 'P']

    for prefix in PREFIXES:
        if size < 1000:
            break
        size /= 1000


    if size > 100 or not prefix:
        fmt = '%.0f'
    elif size > 10:
        fmt = '%.1f'
    else:
        fmt = '%.2f'

    return fmt % size + ' ' + prefix + unit