[melbourne-pug] os.walk into a skip

Mike Dewhirst miked at dewhirst.com.au
Wed Mar 3 07:21:07 CET 2010


On 3/03/2010 4:18pm, Tobias Sargeant wrote:
>
> On 03/03/2010, at 4:09 PM, Mike Dewhirst wrote:
>
>> Hi all
>>
>> Can someone tell me how to skip some arbitrary directories in os.walk()?
>
>
> from the os.walk() docstring:
>
> When topdown is true, the caller can modify the dirnames list in-place
> (e.g., via del or slice assignment), and walk will only recurse into the
> subdirectories whose names remain in dirnames; this can be used to prune
> the search, or to impose a specific order of visiting. Modifying
> dirnames when topdown is false is ineffective, since the directories in
> dirnames have already been generated by the time dirnames itself is
> generated.

for dirpath, dirnames, filenames in os.walk(self.startin, topdown=True):
     #do stuff

I found adjusting dirnames is too late. If I find a "flag" in a 
directory that means it exists in the filenames list - which is easy 
enought to test for. However, the dirnames list is no use because it 
lists the sub-directories alongside the files in that same parent 
directory - dirpath. It is dirpath I want to avoid if it contains the flag.

I had tried to use 'continue' if the flag was encountered but that 
didn't work (for me). I had expected the for statement to skip all 
remaining "stuff" and go on with the next dirpath. I'm obviously missing 
something there.

I have got it working by appending dirpath to a list of excluded dirs 
and then checking that before doing stuff. Here is the working code:

for dirpath, dirnames, filenames in os.walk(self.startin, topdown=True):
     if SKIPFLAG in filenames:
         #continue
         self.exclude_dirs.append(dirpath)
     # case-insensitively check if dirpath is in self.exclude_dirs
     if self.is_excluded_dir(dirpath):
         self.logprint('\n' + dirpath + " is excluded")
     else:
         #do stuff

Thanks again

Mike




>
> _______________________________________________
> melbourne-pug mailing list
> melbourne-pug at python.org
> http://mail.python.org/mailman/listinfo/melbourne-pug
>
>



More information about the melbourne-pug mailing list