should os.walk return a list instead of a tuple?

Duncan Booth duncan.booth at invalid.invalid
Tue Mar 21 04:51:15 EST 2006


Ministeyr wrote:

> When walking top to bottom, it allows you to choose the directories
> you want to visit dynamically by changing the second parameter of the
> tuple (a list of directories). However, since it is a tuple, you
> cannot use "filter" on it, since it would mean reassigning it:
> 
> for dir_tuple in os.walk('/home'):
>      dir_tuple[1]=filter(lambda x: not x.startswith('.'),
>      dir_tuple[1])           
> #do not show hidden files
>      print dir_tuple          #just print the directory and its
>      contents in the 
> simplest possible way
> 
> If os.walk did return a list of three items instead of a tuple, that 
> would become possible.

But you don't need to assign to it, you simply need to mutate it:

   for dir, subdirs, files in os.walk('/home'):
       subdirs[:] = [d for d in subdirs if not d.startswith('.')]
       print dir, subdirs, files

(and if you are desparate to use filter+lambda that works as well.)



More information about the Python-list mailing list