[Tutor] critique my script!

Christopher Spears cspears2002 at yahoo.com
Thu Aug 3 06:14:23 CEST 2006


I created a function that takes a pattern and a base
path and then uses os.walk and glob to traverse
directories starting from the base path and place
files that match the glob pattern in a dictionary.

#!/usr/bin/python

import os, os.path, glob

def glob_files(pattern, base = '.'):
	path_list = []
	abs_base = os.path.abspath(base)
	path_list.append(abs_base)
	for root,dirs,files in os.walk(abs_base):
		for name in dirs:
			path = os.path.join(root, name)
			#print path
			path_list.append(path)
	globbed = {}
	cwd = os.getcwd()
	for p in path_list:
		os.chdir(p)
		matched_files = glob.glob(pattern)
		if matched_files != []:
			globbed[p] = matched_files
		os.chdir(abs_base)
	os.chdir(cwd)
	return globbed
		
Tell me what you think.  This script would probably
have been easier to write with reqular expressions,
but I was determined to use glob.


More information about the Tutor mailing list