Simple py script to calc folder sizes

Ben Cartwright bencvt at gmail.com
Thu Mar 30 19:18:50 EST 2006


Caleb Hattingh wrote:
> Your code works on some folders but not others.   For example, it works
> on my /usr/lib/python2.4 (the example you gave), but on other folders
> it terminates early with StopIteration exception on the
> os.walk().next() step.
>
> I haven't really looked at this closely enough yet, but it looks as
> though there may be an issue with permissions (and not having enough)
> on subfolders within a tree.

You're quite correct.  Here's a version of John's code that handles
such cases:

import warnings
def foldersize(fdir):
   """Returns the size of all data in folder fdir in bytes"""
   try:
      root, dirs, files = os.walk(fdir).next()
   except StopIteration:
      warnings.warn("Could not access " + fdir)
      return 0
   files = [os.path.join(root, x) for x in files]
   dirs = [os.path.join(root, x) for x in dirs]
   return sum(map(os.path.getsize, files)) + sum(map(foldersize, dirs))

There's also another bug in the prettier() function that barfs on empty
directories, as it's taking the log of 0.  The fix:

   exponent = int(math.log(max(1, bytesize), 1024))

--Ben




More information about the Python-list mailing list