I am using a library that reads a file and returns its size in bytes.
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?
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.
There is hurry.filesize that will take the size in bytes and make a nice string out if it.
Or if you want 1K == 1000 (which is what most users assume):
It has IEC support as well (but that wasn't documented):
Because it's written by the Awesome Martijn Faassen, the code is small, clear and extensible. Writing your own systems is dead easy.
Here is one:
Used like so:
Here is the compact function to calculate size
For more detailed output and vice versa operation please refer: http://code.activestate.com/recipes/578019-bytes-to-human-human-to-bytes-converter/
Here's another version of @romeo's reverse implementation that handles a single input string.
Just in case anyone's searching for the reverse of this problem (as I sure did) here's what works for me:
Here my two cents, which permits casting up and down, and adds customizable precision:
Add
TB
, etc, as you wish.Here is what I use:
NB : size should be sent in Bytes.