Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python libraries to calculate human readable filesize from bytes?

I find hurry.filesize very useful but it doesn't give output in decimal?

For example:

print size(4026, system=alternative) gives 3 KB.

But later when I add all the values I don't get the exact sum. For example if the output of hurry.filesize is in 4 variable and each value is 3. If I add them all, I get output as 15.

I am looking for alternative of hurry.filesize to get output in decimals too.

like image 538
pynovice Avatar asked Feb 21 '13 07:02

pynovice


People also ask

Which file is human readable in Python?

Humre is a Python module that gives a more human-readable syntax that works better with code editing tools. You can install Humre just like any other Python module with pip install humre and the full documentation is available in the git repo's README file.

Which Python function will allow a developer to get the size of a file in bytes?

The python os module has stat() function where we can pass the file name as argument. This function returns a tuple structure that contains the file information. We can then get its st_size property to get the file size in bytes.

Which of the following calculates size of the file in Python?

Example 1: Using os module Using stat() from the os module, you can get the details of a file. Use the st_size attribute of stat() method to get the file size.


1 Answers

This isn't really hard to implement yourself:

suffixes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB']
def humansize(nbytes):
    i = 0
    while nbytes >= 1024 and i < len(suffixes)-1:
        nbytes /= 1024.
        i += 1
    f = ('%.2f' % nbytes).rstrip('0').rstrip('.')
    return '%s %s' % (f, suffixes[i])

Examples:

>>> humansize(131)
'131 B'
>>> humansize(1049)
'1.02 KB'
>>> humansize(58812)
'57.43 KB'
>>> humansize(68819826)
'65.63 MB'
>>> humansize(39756861649)
'37.03 GB'
>>> humansize(18754875155724)
'17.06 TB'
like image 129
nneonneo Avatar answered Nov 07 '22 19:11

nneonneo