Wednesday, February 18, 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