在递归函数中产生

编程入门 行业动态 更新时间:2024-10-19 08:53:47
本文介绍了在递归函数中产生的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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

更多推荐

在递归函数中产生

本文发布于:2023-11-02 17:13:08,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1552961.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:递归   函数

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!