Bytes/File Size Format Function
Tim Roberts
timr at probo.com
Wed Jun 13 03:39:11 EDT 2007
samuraisam <samuraiblog at gmail.com> wrote:
>
>Quick file size formatting for all those seekers out there...
>
>import math
>
>def filesizeformat(bytes, precision=2):
> """Returns a humanized string for a given amount of bytes"""
> bytes = int(bytes)
> if bytes is 0:
> return '0bytes'
> log = math.floor(math.log(bytes, 1024))
> return "%.*f%s" % (
> precision,
> bytes / math.pow(1024, log),
> ['bytes', 'kb', 'mb', 'gb', 'tb','pb', 'eb', 'zb', 'yb']
>[int(log)]
> )
I have a couple of picky comments. The abbreviation for "bytes" should be
"B"; small "b" is bits by convention. All of the prefixes above "k" should
be capitalized: kB, MB and GB, not mb and gb.
The truly anal retentive would probably argue that you should be using kiB,
MiB, and GiB, since you are basing your scale on 1024 instead of 1000.
--
Tim Roberts, timr at probo.com
Providenza & Boekelheide, Inc.
More information about the Python-list
mailing list