[Tutor] critique my script!

Christopher Spears cspears2002 at yahoo.com
Thu Aug 3 17:33:46 CEST 2006


I didn't know I could place the glob in the os.walk
traversal.  Could you give me an example of how to do
this?

--- Alan Gauld <alan.gauld at freenet.co.uk> wrote:

> >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
> 


"I'm the last person to pretend that I'm a radio.  I'd rather go out and be a color television set."
-David Bowie

"Who dares wins"
-British military motto

"I generally know what I'm doing."
-Buster Keaton


More information about the Tutor mailing list