[Tutor] Getting os.walk output into a list
Paradox
paradox at pobox.com
Fri Mar 15 06:53:22 CET 2013
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.
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?
More information about the Tutor
mailing list