Showing posts with label directory. Show all posts
Showing posts with label directory. Show all posts

Sunday, July 5, 2009

Recursively removing empty directories using python


#!/usr/bin/python
import os
from os.path import join
def remEmptyDir(mypath):
for root, dirs, files in os.walk(mypath,topdown=False):
for name in dirs:
fname = join(root,name)
if not os.listdir(fname): #to check wither the dir is empty
print fname
os.removedirs(fname)

remEmptyDir('/home/suresh/photos')

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.

#!/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