admin
admin
7478 2 0

python 根据字节计算文件大小(k/m/g)的函数

根据字节计算文件的大小

def str_filesize(size):
    """
    >>> print str_filesize(0)
    0
    >>> print str_filesize(1023) 
    1023
    >>> print str_filesize(1024)
    1K
    >>> print str_filesize(1024*2)
    2K
    >>> print str_filesize(1024**2-1)
    1023K
    >>> print str_filesize(1024**2)
    1M
    """
    import bisect
    d = [(1024-1,'K'), (1024**2-1,'M'), (1024**3-1,'G'), (1024**4-1,'T')]
    s = [x[0] for x in d]
    index = bisect.bisect_left(s, size) - 1
    if index == -1:
        return str(size)
    else:
        b, u = d[index]
    return str(size / (b+1)) + u
0

See Also

Nearby


Discussion (2)

沐雨
沐雨 2014-10-30 15:53

测试代码

$newest_nodes = get_newest_nodes();
if(count($newest_nodes)==$options['newest_node_num']){
    $bot_nodes = get_bot_nodes();
}

$show_sider_ad = "1";
$links = get_links();```
0
q26486328
q26486328 2014-10-30 15:56

不知道楼主是在用youbbs 吗

0
Login Topics