'filesize' patch for humanize

17 views
Skip to first unread message

Jay Parlar

unread,
Aug 1, 2006, 4:10:41 PM8/1/06
to django-d...@googlegroups.com
I just added a patch (http://code.djangoproject.com/ticket/2466) that
adds a 'filesize' filter, which returns filesizes (from get_XXX_size)
in a human friendly way.

It's trivially simple, but I thought it might be useful to others.

Jay P.

Jay Parlar

unread,
Aug 1, 2006, 4:26:47 PM8/1/06
to django-d...@googlegroups.com
Oh jeez, I just noticed the 'filesizeformat' filter...

Well, there's 5 minutes of my life I'll never get back :)

Jay P.

Gary Wilson

unread,
Aug 3, 2006, 12:15:30 AM8/3/06
to Django developers
Just thought I might share a size converter I wrote a while back...

def bytesToHumanReadable(bytes, binary=True, precision=1):
"""Convert bytes to a human-readable size.
Given a size in bytes, this function converts it and uses the
largest
suffix possible that does not result in a size that is less than 1
(i.e. 300 KiB instead of 0.3 MiB). By default use binary
size-prefixes,
and if binary=False then use SI size-prefixes.
"""

if binary:
factor = 1024
suffixes = [
'B', # bytes
'KiB', # kibibytes
'MiB', # mebibytes
'GiB', # gibibytes
'TiB', # tebibytes
'PiB', # pebibytes
'EiB', # exbibytes
'ZiB', # zebibytes
'YiB', # yobibytes
]
else:
factor = 1000
suffixes = [
'B', # bytes
'KB', # kilobytes
'MB', # megabytes
'GB', # gigabytes
'TB', # terabytes
'PB', # petabytes
'EB', # exabytes
'ZB', # zettabytes
'YB', # yottabytes
]
format = '%.*f %s'
# Change to float so we don't lose precision in the division
operation.
size = float(bytes)
for suffix in suffixes:
if size >= factor:
size /= factor
else:
if suffix is suffixes[0]:
# Do not use precision for size in bytes.
precision = 0
return format % (precision, size, suffix)
# We are at the end of the suffix list, anything this big gets put
into
# units of the last suffix in the list.
return format % (precision, size, suffixes[-1])


Some examples:
>>> bytesToHumanReadable(1023)
'1023 B'
>>> bytesToHumanReadable(1024)
'1.0 KiB'
>>> bytesToHumanReadable(3215436)
'3.1 MiB'
>>> bytesToHumanReadable(998436)
'975.0 KiB'
>>> bytesToHumanReadable(163456887454)
'152.2 GiB'
>>> bytesToHumanReadable(163456887454, binary=False)
'163.5 GB'
>>> bytesToHumanReadable(163456887454, binary=False, precision=8)
'163.45688745 GB'
>>> bytesToHumanReadable(16345688745446468445546546)
'13.5 YiB'

Reply all
Reply to author
Forward
0 new messages