#!/usr/bin/python # dirsize.py # Author: Leston Buell # Modified: December 20, 2000 # Purpose: Give example of os.path.walk(). # The program calculates size of directory # (current directory by default), recursively # including contents of all daughter directories. # Note that this may take a minute to run if you're # checking a large directory. # No checking has been done to detect links. # This might cause infinite loops on a Unix-like platform. import os, sys class Adder : # An Adder object is passed as the 'arg' argument of # os.path.walk. This adder object is acted upon in the # addSizes function, which is the 'visitfunc' argument of # os.path.walk. def __init__( self ) : self.total = 0 def add( self, integer ) : self.total = self.total + integer def getTotal( self ) : return self.total def addSizes( adder, dirname, names ) : for name in names : fullpath = os.path.join( dirname, name ) try : size = os.path.getsize( fullpath ) except : size = 0 adder.add( size ) if __name__ == '__main__' : adder = Adder() try : dirname = sys.argv[1] except : dirname = '.' ################################# # Here's the os.path.walk part. # ################################# os.path.walk( dirname, addSizes, adder ) size = adder.getTotal() print "Directory: " + os.path.abspath( dirname ) print "Total size: " + `size` + " bytes"