[Tutor] critique my script!

Kent Johnson kent37 at tds.net
Fri Aug 4 04:39:10 CEST 2006


Christopher Spears wrote:
> 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?

The base_path directory will never appear in the dirs list from 
os.walk(). It will be returned as the root directory however. You could 
modify your program to glob the root directory instead of the list of 
dirs. Or use fnmatch.fnmatch() or fnmatch.filter(), which I still think 
is a better solution if you aren't married to glob():

import os, fnmatch

def glob_files(pattern, base_path = '.'):
	abs_base = os.path.abspath(base_path)
	globbed_dict = {}
	for root,dirs,files in os.walk(abs_base):
		matched_files = [ os.path.join(root, name) for name in fnmatch.filter(files, pattern) ]

		if matched_files: # Note: no need to compare to []
			globbed_dict[root] = matched_files
	return globbed_dict

Kent



More information about the Tutor mailing list