(Disclaimer: Python 3 only!)
Something with syntax similar to what you want is to use the splat operator to expand the two generators:
for directory, dirs, files in (*os.walk(directory_1), *os.walk(directory_2)):
do_something()
Explanation:
This effectively performs a single-level flattening of the two generators into an N-tuple of 3-tuples (from os.walk
) that looks like:
((directory1, dirs1, files1), (directory2, dirs2, files2), ...)
Your for-loop then iterates over this N-tuple.
Of course, by simply replacing the outer parentheses with brackets, you can get a list of 3-tuples instead of an N-tuple of 3-tuples:
for directory, dirs, files in [*os.walk(directory_1), *os.walk(directory_2)]:
do_something()
This yields something like:
[(directory1, dirs1, files1), (directory2, dirs2, files2), ...]
Pro:
The upside to this approach is that you don't have to import anything and it's not a lot of code.
Con:
The downside is that you dump two generators into a collection and then iterate over that collection, effectively doing two passes and potentially using a lot of memory.
itertools.chain()
does not return atypes.GeneratorType
instance. Just in case the exact type is crucial. – Darindaring