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.


#!/usr/bin/python
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)
try:
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)
os.chdir(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

Advertisements

Responses

  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:

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

Categories

%d bloggers like this: