[Tutor] critique my script!
Alan Gauld
alan.gauld at freenet.co.uk
Thu Aug 3 12:40:03 CEST 2006
>I created a function that takes a pattern and a base
> path and then uses os.walk and glob to traverse
> directories starting from the base path and place
> files that match the glob pattern in a dictionary.
I'm not sure why you are traversing the paths a second time.
Why not just apply glob within the os.walk traversal?
After all you are putting the path into the path list, then
iterating over that list later, why not just apply glob the
first time around?
> #!/usr/bin/python
>
> import os, os.path, glob
>
> def glob_files(pattern, base = '.'):
> path_list = []
> abs_base = os.path.abspath(base)
> path_list.append(abs_base)
> for root,dirs,files in os.walk(abs_base):
> for name in dirs:
> path = os.path.join(root, name)
> #print path
> path_list.append(path)
> globbed = {}
> cwd = os.getcwd()
> for p in path_list:
> os.chdir(p)
> matched_files = glob.glob(pattern)
> if matched_files != []:
> globbed[p] = matched_files
> os.chdir(abs_base)
> os.chdir(cwd)
> return globbed
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld
More information about the Tutor
mailing list