[melbourne-pug] os.walk into a skip

Darius Powell dariusp686 at gmail.com
Wed Mar 3 10:43:34 CET 2010


Try adding

dirnames[:] = []

in there where you detect the SKIPFLAG file so that it doesn't
traverse into the sub dirs. continue only starts the next loop, it
does not alter the behaviour of os.walk - modifying dirnames does.

On 3 March 2010 17:21, Mike Dewhirst <miked at dewhirst.com.au> wrote:
> 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
>>
>>
>
> _______________________________________________
> 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