os.walk一次多个目录

Joh*_*ann 11 python os.walk

可能重复:
如何在Python中连接两个生成器?

有没有办法在python中使用os.walk一次遍历多个目录?

my_paths = []
path1 = '/path/to/directory/one/'
path2 = '/path/to/directory/two/'
for path, dirs, files in os.walk(path1, path2):
    my_paths.append(dirs)
Run Code Online (Sandbox Code Playgroud)

上面的例子不起作用(因为os.walk只接受一个目录),但我希望有一个更优雅的解决方案,而不是两次调用os.walk(加上我可以一次排序).谢谢.

agf*_*agf 25

要将多个iterables视为一个,请使用itertools.chain:

from itertools import chain

paths = ('/path/to/directory/one/', '/path/to/directory/two/', 'etc.', 'etc.')
for path, dirs, files in chain.from_iterable(os.walk(path) for path in paths):
Run Code Online (Sandbox Code Playgroud)


Dav*_*nan 6

使用itertools.chain().

for path, dirs, files in itertools.chain(os.walk(path1), os.walk(path2)):
    my_paths.append(dirs)
Run Code Online (Sandbox Code Playgroud)


Ste*_*ski 5

其他人也提到过itertools.chain

还可以选择再嵌套一层:

my_paths = []
for p in ['/path/to/directory/one/', '/path/to/directory/two/']:
    for path, dirs, files in os.walk(p):
        my_paths.append(dirs)
Run Code Online (Sandbox Code Playgroud)