from time import time import os, string, fnmatch, sys def Walk( root, recurse=0, pattern='*', return_folders=0, print_dirs=0 ): # initialize result = [] # must have at least root folder try: names = os.listdir(root) except os.error: return result # expand pattern pattern = pattern or '*' pat_list = string.splitfields( pattern , ';' ) # check each file for name in names: fullname = os.path.normpath(os.path.join(root, name)) # grab if it matches our pattern and entry type for pat in pat_list: if fnmatch.fnmatch(name, pat): if os.path.isfile(fullname) or (return_folders and os.path.isdir(fullname)): result.append(fullname) continue # recursively scan other folders, appending results if recurse: if os.path.isdir(fullname) and not os.path.islink(fullname): if print_dirs and print_dirs != 1: print print_dirs, else: print fullname result = result + Walk( fullname, recurse, pattern, return_folders, print_dirs ) return result if __name__ == '__main__': # test code ## print '\nExample 1:' ## files = Walk('.', 1, '*', 1) ## print 'There are %s files below current location:' % len(files) ## for file in files: ## print file print '\nRemove all *.nws and *.eml files:' t0 = time() files = Walk('D:\\', 1, '*.nws;*.eml', print_dirs=".") +\ Walk('C:\\', 1, '*.nws;*.eml', print_dirs=".") print "\n\n" print 'There are %s files below current location:' % len(files) for file in files: print file os.remove(file) t1 = time() print "Test took:", round(t1-t0,1), " seconds" ok = raw_input("\nPress Enter to exit") sys.exit(1)