在Python中转换文件大小的更好方法 [英] Better way to convert file sizes in Python

查看:134
本文介绍了在Python中转换文件大小的更好方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一个读取文件并返回其大小(以字节为单位)的库.

I am using a library that reads a file and returns its size in bytes.

此文件大小然后显示给最终用户;为了使他们更容易理解,我将文件大小除以1024.0 * 1024.0,从而将文件大小明确转换为MB.当然可以,但是我想知道在Python中有更好的方法吗?

This file size is then displayed to the end user; to make it easier for them to understand it, I am explicitly converting the file size to MB by dividing it by 1024.0 * 1024.0. Of course this works, but I am wondering is there a better way to do this in Python?

更好的是,我的意思是也许一个stdlib函数可以根据我想要的类型操纵大小.就像我指定MB一样,它会自动将其除以1024.0 * 1024.0.在这些线上有些东西.

By better, I mean perhaps a stdlib function that can manipulate sizes according to the type I want. Like if I specify MB, it automatically divides it by 1024.0 * 1024.0. Somethign on these lines.

推荐答案

hurry.filesize ,它将以字节为单位,如果有的话,会给出一个漂亮的字符串.

There is hurry.filesize that will take the size in bytes and make a nice string out if it.

>>> from hurry.filesize import size
>>> size(11000)
'10K'
>>> size(198283722)
'189M'

或者如果您希望1K == 1000(这是大多数用户的假设):

Or if you want 1K == 1000 (which is what most users assume):

>>> from hurry.filesize import size, si
>>> size(11000, system=si)
'11K'
>>> size(198283722, system=si)
'198M'

它也具有IEC支持(但没有记录):

It has IEC support as well (but that wasn't documented):

>>> from hurry.filesize import size, iec
>>> size(11000, system=iec)
'10Ki'
>>> size(198283722, system=iec)
'189Mi'

由于它是由Martijn Faassen编写的,因此该代码小巧,清晰且可扩展.编写自己的系统非常简单.

Because it's written by the Awesome Martijn Faassen, the code is small, clear and extensible. Writing your own systems is dead easy.

这里是一个:

mysystem = [
    (1024 ** 5, ' Megamanys'),
    (1024 ** 4, ' Lotses'),
    (1024 ** 3, ' Tons'), 
    (1024 ** 2, ' Heaps'), 
    (1024 ** 1, ' Bunches'),
    (1024 ** 0, ' Thingies'),
    ]

使用方式如下:

>>> from hurry.filesize import size
>>> size(11000, system=mysystem)
'10 Bunches'
>>> size(198283722, system=mysystem)
'189 Heaps'

这篇关于在Python中转换文件大小的更好方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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