Yield in a recursive function

后端 未结 9 501
独厮守ぢ
独厮守ぢ 2021-01-30 10:49

I am trying to do something to all the files under a given path. I don\'t want to collect all the file names beforehand then do something with them, so I tried this:

<         


        
相关标签:
9条回答
  • 2021-01-30 11:16

    Change this:

    explore(path)
    

    To this:

    for subpath in explore(path):
        yield subpath
    

    Or use os.walk, as phooji suggested (which is the better option).

    0 讨论(0)
  • 2021-01-30 11:17

    Use os.walk instead of reinventing the wheel.

    In particular, following the examples in the library documentation, here is an untested attempt:

    import os
    from os.path import join
    
    def hellothere(somepath):
        for root, dirs, files in os.walk(somepath):
            for curfile in files:
                yield join(root, curfile)
    
    
    # call and get full list of results:
    allfiles = [ x for x in hellothere("...") ]
    
    # iterate over results lazily:
    for x in hellothere("..."):
        print x
    
    0 讨论(0)
  • 2021-01-30 11:17

    The problem is this line of code:

    explore(path)
    

    What does it do?

    • calls explore with the new path
    • explore runs, creating a generator
    • the generator is returned to the spot where explore(path) was executed . . .
    • and is discarded

    Why is it discarded? It wasn't assigned to anything, it wasn't iterated over -- it was completely ignored.

    If you want to do something with the results, well, you have to do something with them! ;)

    The easiest way to fix your code is:

    for name in explore(path):
        yield name
    

    When you are confident you understand what's going on, you'll probably want to use os.walk() instead.

    Once you have migrated to Python 3.3 (assuming all works out as planned) you will be able to use the new yield from syntax and the easiest way to fix your code at that point will be:

    yield from explore(path)
    
    0 讨论(0)
提交回复
热议问题