Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better way to convert file sizes in Python [closed]

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.

like image 816
user225312 Avatar asked Mar 04 '11 13:03

user225312


People also ask

How do I check if a file size is greater than 0 in Python?

Use os.path.getsize() function Use the os. path. getsize('file_path') function to check the file size. Pass the file name or file path to this function as an argument.


2 Answers

Here is what I use:

import math  def convert_size(size_bytes):    if size_bytes == 0:        return "0B"    size_name = ("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB")    i = int(math.floor(math.log(size_bytes, 1024)))    p = math.pow(1024, i)    s = round(size_bytes / p, 2)    return "%s %s" % (s, size_name[i]) 

NB : size should be sent in Bytes.

like image 112
James Avatar answered Sep 17 '22 20:09

James


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' 

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' 

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' 

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:

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

Used like so:

>>> from hurry.filesize import size >>> size(11000, system=mysystem) '10 Bunches' >>> size(198283722, system=mysystem) '189 Heaps' 
like image 34
Lennart Regebro Avatar answered Sep 18 '22 20:09

Lennart Regebro