可重用的库以获得人类可读的文件大小? [英] Reusable library to get human readable version of file size?

查看:69
本文介绍了可重用的库以获得人类可读的文件大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

网络上有各种各样的代码片段,可为您提供从字节大小返回人类可读大小的功能:

There are various snippets on the web that would give you a function to return human readable size from bytes size:

>>> human_readable(2048)
'2 kilobytes'
>>>

但是有Python库提供此功能吗?

But is there a Python library that provides this?

推荐答案

通过简单的实现解决了上述任务太少,需要库的问题:

Addressing the above "too small a task to require a library" issue by a straightforward implementation:

def sizeof_fmt(num, suffix='B'):
    for unit in ['','Ki','Mi','Gi','Ti','Pi','Ei','Zi']:
        if abs(num) < 1024.0:
            return "%3.1f%s%s" % (num, unit, suffix)
        num /= 1024.0
    return "%.1f%s%s" % (num, 'Yi', suffix)

支持:


  • 所有当前已知的二进制前缀

  • 负数和正数

  • 大于1000 Yobibytes的数字

  • 任意单位(也许您想

  • all currently known binary prefixes
  • negative and positive numbers
  • numbers larger than 1000 Yobibytes
  • arbitrary units (maybe you like to count in Gibibits!)

例如:

>>> sizeof_fmt(168963795964)
'157.4GiB'

通过弗雷德·西雷拉(Fred Cirera)

这篇关于可重用的库以获得人类可读的文件大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆