Yield in a recursive function

后端 未结 9 505
独厮守ぢ
独厮守ぢ 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: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
    

提交回复
热议问题