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)
上面的例子不行(因为os.walk只接受一个目录),但我希望能有一个更优雅的解决方案,而不是调用os.walk两次(这样我还可以一次性对所有结果进行排序)。谢谢。
4 个回答
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)
7
for path, dirs, files in itertools.chain(os.walk(path1), os.walk(path2)):
my_paths.append(dirs)
33
如果你想把多个可迭代对象(比如列表、元组等)当作一个整体来处理,可以使用 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):