美文网首页Python代码库
字节数转换成对应的文件大小符号(KMGTP)

字节数转换成对应的文件大小符号(KMGTP)

作者: 马仔 | 来源:发表于2017-01-20 21:57 被阅读53次
    def bytes2human(n):
      """
      >>> bytes2human(10000)
      9K
      >>> bytes2human(100001221)
      95M
      """
      symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
      prefix     = {}
      for i, s in enumerate(symbols):
          prefix[s] = 1 << (i+1)*10
    
      for s in reversed(symbols):
          if n >= prefix[s]:
              value = int(float(n)/prefix[s])
              return '%s%s' % (value, s)
      return '%sB' % n
    

    相关文章

      网友评论

        本文标题:字节数转换成对应的文件大小符号(KMGTP)

        本文链接:https://www.haomeiwen.com/subject/tsdgbttx.html