获取可读的文件大小版本?
这是一个用来将字节大小转换成易于理解的人类可读格式的函数:
>>> human_readable(2048)
'2 kilobytes'
>>>
这个怎么做呢?
30 个回答
49
下面的内容在Python 3.6及以上版本中可以使用,我认为这是这里最容易理解的答案,并且可以让你自定义小数点后的位数。
def human_readable_size(size, decimal_places=2):
for unit in ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB']:
if size < 1024.0 or unit == 'PiB':
break
size /= 1024.0
return f"{size:.{decimal_places}f} {unit}"
201
你想要的功能似乎都可以在一个叫做 humanize
的库里找到。这个库里的 humanize.naturalsize()
方法好像能满足你的所有需求。
下面是一个示例代码(适用于 python 3.10
)
import humanize
disk_sizes_list = [1, 100, 999, 1000,1024, 2000,2048, 3000, 9999, 10000, 2048000000, 9990000000, 9000000000000000000000]
for size in disk_sizes_list:
natural_size = humanize.naturalsize(size)
binary_size = humanize.naturalsize(size, binary=True)
print(f" {natural_size} \t| {binary_size}\t|{size}")
输出结果
1 Byte | 1 Byte |1
100 Bytes | 100 Bytes |100
999 Bytes | 999 Bytes |999
1.0 kB | 1000 Bytes |1000
1.0 kB | 1.0 KiB |1024
2.0 kB | 2.0 KiB |2000
2.0 kB | 2.0 KiB |2048
3.0 kB | 2.9 KiB |3000
10.0 kB | 9.8 KiB |9999
10.0 kB | 9.8 KiB |10000
2.0 GB | 1.9 GiB |2048000000
10.0 GB | 9.3 GiB |9990000000
9.0 ZB | 7.6 ZiB |9000000000000000000000
758
针对上面提到的“这个任务太小,不需要用到库”的问题,这里提供了一个简单的实现方法(使用了f-strings,所以需要Python 3.6及以上版本):
def sizeof_fmt(num, suffix="B"):
for unit in ("", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei", "Zi"):
if abs(num) < 1024.0:
return f"{num:3.1f}{unit}{suffix}"
num /= 1024.0
return f"{num:.1f}Yi{suffix}"
这个实现支持:
- 所有目前已知的二进制前缀
- 正数和负数
- 大于1000 Yobibytes的数字
- 任意单位(也许你喜欢用Gibibits来计数!)
示例:
>>> sizeof_fmt(168963795964)
'157.4GiB'
作者:Fred Cirera