[Tutor] critique my script!

Kent Johnson kent37 at tds.net
Thu Aug 3 13:20:20 CEST 2006


Alan Gauld 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?

Alternately you could use fnmatch.fnmatch() to filter the list of files 
received from os.walk(). Then you wouldn't be using glob() but fnmatch() 
is the file-name-matching part of glob(). A list comprehension would be 
good for this:
matchedFiles = [ f for f in files if fnmatch(f, pattern) ]

I think your whole program can be written in about six lines, but I'll 
let you puzzle it a bit rather than showing you.

Kent



More information about the Tutor mailing list