Size of files in human, readable form

Martin Pool martinp at mincom.com
Tue Dec 21 03:06:45 EST 1999


Thomas Weholt wrote:

> Just wondered if there are any modules/methods/ways to get a file`s size
> in kilobytes or megabytes etc, based on what`s appropriate? Probably a
> simple thing to do, but my attempts have failed.

As tim muddletin said, 

>>> import os,sys
>>> os.path.getsize(sys.executable)
24638
>>> os.stat(sys.executable)[6]
24638
>>>

to get the size of the file, and then something like this to convert to
human-readable form:

_abbrevs = [
    (1<<50L, 'P'),
    (1<<40L, 'T'), 
    (1<<30L, 'G'), 
    (1<<20L, 'M'), 
    (1<<10L, 'k'),
    (1, '')
    ]

def greek(size):
    """Return a string representing the greek/metric suffix of a size"""
    for factor, suffix in _abbrevs:
        if size > factor:
            break
    return `int(size/factor)` + suffix

You can change the comparison or int if you'd prefer to see things like
"3023kb" or "3.02Mb".

-- 
 /\\\  Mincom | Martin Pool          | martinp at mincom.com
// \\\        | Software Engineer    | Phone: +61 7 3303-3333
\\ ///        | Mincom Limited       | Teneriffe, Brisbane
 \///         | And now a word from our sponsor...

This transmission is for the intended addressee only and is
confidential information. If you have received this
transmission in error, please delete it and notify the
sender. The contents of this E-mail are the opinion of the
writer only and are not endorsed by Mincom Limited unless
expressly stated otherwise.



More information about the Python-list mailing list