[Tutor] critique my script!

Python python at venix.com
Fri Aug 4 01:31:47 CEST 2006


On Thu, 2006-08-03 at 15:37 -0700, 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?

I won't answer for elegance, but you glob the dirs, but do not glob
root.  Now all of your code is knotted together pretty tightly, so it's
hard to make the change.  Suppose we have:

def dirs(abs_base):
	for root,dirs,files in os.walk(abs_base):
		yield root
		for name in dirs:
			yield os.path.join(root, name)

def globdir(path,pattern):
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
-- 
Lloyd Kvam
Venix Corp



More information about the Tutor mailing list