Python Forum

Full Version: 2 iterators or generators
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
i want to be able to interleave two or more iterator or generators, including stepping one or more of them fewer or more times as coded logic may dictate. for example, consider os.walk('file-tree-one') and os.walk('file-tree-two') where these two file trees have identically named files and the 2nd one has an extra file somewhere. normally i can do code like:
    t1 = []
    for dn, dl, fl in os.walk('file-tree-one'):
        for f in fl:
            t1.append(dn+'/'+f)
    print('\n'.join(t1))
and build a flat list of files from the tree (this code sample does not include directories). something has to keep the state of how far along this is as it runs and i assume that would be the iterator. but how would this be done to interleave two of them? some documentation mentions a next() call. i tried a .next() method on os.walk(), but that attribute does not exist. anyone know what is going on?
You can use the built-in function next() with any iterator
t1 = []
walk1 = os.walk('file-tree-one')
while True:
    dn, dl, fl = next(walk1)
    for f in fl:
        t1.append(os.path.join(dn, f))
You need to handle the exception StopIteration or use the 'default' parameter in next().