Christopher Spears wrote: > 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 > As written create_dict() has the side-effect of changing the working dir, which you correct for in the caller. A better design would be to save and restore the correct dir in create_dict() so callers don't have to know that it has changed. > 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 > Rather than special-casing abs_base with its own call to create_dict, I would have the os.walk() loop act on root instead of dirs:
for root,dirs,files in os.walk(abs_base): globbed_dict = create_dict(root, globbed_dict) > > def print_dict(globbed_dict): > paths = globbed_dict.keys() > paths.sort() > for p in paths: > Could be written more succinctly as for p in sorted(globbed_dict.keys()): Kent > 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) > > > > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > > _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor