[Tutor] Getting os.walk output into a list

Dave Angel davea at davea.name
Fri Mar 15 07:31:55 CET 2013


On 03/15/2013 01:53 AM, Paradox wrote:
> There is something I can't figure out about the following code (using
> python 2.7.3):
>
> def return_tree_files(rootpath, pattern):
>      for root, dirs, files in os.walk(rootpath):
>          i = [os.path.join(root, filename) for filename in
> fnmatch.filter(files, pattern)]
>          return i
>
> I thought the function would return a list of lists of filenames in the
> rootpath and all subfolders.  Instead I get only the filenames that
> match the pattern in the rootpath, it doesn't go into the subfolders.

That's because you returned out of the loop, the first time through. 
Each time through the loop, it describes one directory.  Since your 
return after the first one, that's the only directory you'll see.

>
> If I replace the last line with 'print i' instead of 'return i' I get
> output closer to what I expect but what I really want is a list of lists
> I can use elsewhere.
>
> I know I could collect these and append them but I am trying to
> understand list comprehensions and os.walk - but I have hit a wall.
>
> Why does the list comprehension only go down the rootpath once and stop,
> not walking to the subfolders?
>
>

The list comprehension builds a list for the one directory.  If you want 
them all, you'll have to append those lists into another list, giving 
you a nested list.


-- 
DaveA


More information about the Tutor mailing list