os.walk() dirs and files

George Sakkis george.sakkis at gmail.com
Wed Feb 8 13:56:09 EST 2006


rtilley wrote:
> Duncan Booth wrote:
>
>> How about just concatentating the two lists:
>>
>>> for root, dirs, files in os.walk(path):
>>
>>        for fs_object in files + dirs:
>>
>>>         ADD fs_object to dictionary
>
>
> Thank you Duncan! that solves the problem perfectly!

Or a bit more efficiently (no need to allocate a new list for storing
files+dirs):

from itertools import chain
for root, dirs, files in os.walk(path):
	for fs_object in chain(files,dirs):
		ADD fs_object to dictionary

Or you can download the path.py module
(http://www.jorendorff.com/articles/python/path/):

from path import path
for fs_object in path(root).walk():
	ADD fs_object to dictionary


George




More information about the Python-list mailing list