Size of files in human, readable form
Oleg Broytmann
phd at phd.russ.ru
Tue Dec 21 06:54:44 EST 1999
Hans,
this is definetely for your snippets collection. Excellent example of
code.
On Tue, 21 Dec 1999, Martin Pool wrote:
> 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".
>
>
Oleg.
----
Oleg Broytmann Foundation for Effective Policies phd at phd.russ.ru
Programmers don't die, they just GOSUB without RETURN.
More information about the Python-list
mailing list