[Tutor] critique my script again!

Christopher Spears cspears2002 at yahoo.com
Fri Aug 4 06:03:25 CEST 2006


Here is the complete script with documentation:

#!/usr/bin/python

#This script prompts the user for a path and a glob
pattern.
#The script firsts looks in the directory denoted by
the path
#for a matching file.  If a match is found, the path
and file are added
#to a dictionary as a key and value.  This process is
repeated for all
#directories underneath the base directory.  Finally,
the directories and
#their corresponding files are formatted and printed
to the screen.
#Next step: rework script as GUI using PyGTK.
#Created by Chris Spears 7/3/06.
#Thanks to tutor at python.org.

import os, os.path, glob

def create_dict(path, globbed_dict):
	os.chdir(path)
	matched_files = glob.glob(pattern)
	if matched_files != []:
		globbed_dict[path] = matched_files
	return globbed_dict

def glob_files(pattern, base_path = '.'):
	abs_base = os.path.abspath(base_path)
	globbed_dict = {}
	cwd = os.getcwd()
	#Check the root directory first
	globbed_dict = create_dict(abs_base, globbed_dict)
	#Check other directories
	for root,dirs,files in os.walk(abs_base):
		for name in dirs:
			path = os.path.join(root, name)
			globbed_dict = create_dict(path, globbed_dict)
			os.chdir(abs_base)
	#Make sure the script returns to the user's original
directory.
	os.chdir(cwd)
	return globbed_dict
	
def print_dict(globbed_dict):
	paths = globbed_dict.keys()
	paths.sort()
	for p in paths:
		print p,": "
		file_list = globbed_dict[p]
		for f in file_list:
			print "\t",f
		
	
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_dict(globbed_dict)
		

	

	



More information about the Tutor mailing list