Posted by: sureshamrita | February 19, 2009

Directory size listing

The following python code lists the subdirectories and files of the given directory in the descending order of their size.

import os

# this function returns the size of the given directory or file.

def getDirectorySize(directory):
if os.path.isfile(directory):
return os.path.getsize(directory)
dir_size = 0
for (path, dirs, files) in os.walk(directory):
for file in files:
filename = os.path.join(path, file)
dir_size += os.path.getsize(filename)
except OSError:
pass #to manage for exampling a missing link etc
return dir_size

#this function lists the directory contents of the
#given directory by calling getDirectorySize(directory)
#to get the size of each directories

def getDirectorySizeListing(directory):
filesize = {}
dir = os.listdir(directory)
for item in dir:
sz = getDirectorySize(item)/2**20 #for converting into megabytes
if sz: filesize[item] = sz

#to sort the dictionary based on values
from operator import itemgetter
filesize = sorted(filesize.iteritems(),key=itemgetter(1),reverse=True)

return filesize

#application code
d = "/home/suresh/"
x = getDirectorySizeListing(d)
for i,val in enumerate(x):
print val


  1. I’ve been following your blog, it’s really good.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s


%d bloggers like this: