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(加上我可以一次排序)。感谢。
答案 0 :(得分:23)
要将多个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):
答案 1 :(得分:4)
for path, dirs, files in itertools.chain(os.walk(path1), os.walk(path2)):
my_paths.append(dirs)
答案 2 :(得分:1)
因为没有人提到它,在这个或其他引用的帖子中:
http://docs.python.org/library/multiprocessing.html
>>> from multiprocessing import Pool
>>> p = Pool(5)
>>> def f(x):
... return x*x
...
>>> p.map(f, [1,2,3])
在这种情况下,你有一个目录列表。对地图的调用将返回每个目录的列表列表,然后您可以选择展平它,或保持结果聚集
def t(p):
my_paths = []
for path, dirs, files in os.walk(p):
my_paths.append(dirs)
paths = ['p1','p2','etc']
p = Pool(len(paths))
dirs = p.map(t,paths)
答案 3 :(得分:0)
其他人提到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)