[Tutor] critique my script!

Christopher Spears cspears2002 at yahoo.com
Fri Aug 4 00:37:49 CEST 2006


I rewrote my code with Alan's suggestions in mind.

#!/usr/bin/python

import os, os.path, glob

def glob_files(pattern, base_path = '.'):
	abs_base = os.path.abspath(base_path)
	#path_list = []
	#path_list.append(abs_base)
	globbed_dict = {}
	cwd = os.getcwd()
	for root,dirs,files in os.walk(abs_base):
		for name in dirs:
			path = os.path.join(root, name)
			print path
			os.chdir(path)
			matched_files = glob.glob(pattern)
			#print matched_files
			if matched_files != []:
				globbed_dict[path] = matched_files
			os.chdir(abs_base)
	os.chdir(cwd)
	return globbed_dict
	
if __name__ == "__main__":
	base_path = raw_input("Enter a base path: ")
	pattern = raw_input("Enter a glob pattern: ")
	
	str(base_path)
	str(pattern)
	
	globbed_dict = glob_files(pattern, base_path)
	
	print globbed_dict

However, the code still doesn't do exactly what I
want.

$ ./~/chris_python 126> ./find_items_01.py
Enter a base path: ./LearningToProgram
Enter a glob pattern: *.pyc
{}

Under the LearningToProgram directory is a test
directory that doesn't contain any .pyc files, so the
script's returned value is correct.  However, .pyc
files exist in the LearningToProgram directory, and I
would like to put those files in the dictionary too. 
Is there an elegant way to accomplish this?




More information about the Tutor mailing list