在递归函数中产生 [英] Yield in a recursive function

查看:150
本文介绍了在递归函数中产生的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对给定路径下的所有文件执行某些操作。我不想事先收集所有文件名,然后用它们做一些事情,所以我尝试了这个:

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:

import os
import stat

def explore(p):
  s = ''
  list = os.listdir(p)
  for a in list:
    path = p + '/' + a
    stat_info = os.lstat(path )
    if stat.S_ISDIR(stat_info.st_mode):
     explore(path)
    else:
      yield path

if __name__ == "__main__":
  for x in explore('.'):
    print '-->', x

但是这个代码在命中它们时跳过目录,而不是放弃它们的内容。我做错了什么?

But this code skips over directories when it hits them, instead of yielding their contents. What am I doing wrong?

推荐答案

使用 os.walk 而不是重新发明轮子。

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

这篇关于在递归函数中产生的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆