贴一段自己写的代码,主要实现以下功能:
- 递归遍历源目录( src_path )下的文件,可以用于检测文件
- 可以将源目录下的所有文件处理后传到目标目录(det_path)中,即可以对源文件批量处理,将 print 替换成对应方法即可
import os def dir_walk(src_path,det_path=None): if os.path.isdir(src_path): if det_path and not os.path.isdir(det_path): os.makedirs(det_path) for name in os.listdir(src_path): _src_path = os.path.join(src_path,name) _det_path = det_path and os.path.join(det_path,name) yield from dir_walk(_src_path,_det_path) if os.path.isfile(src_path): yield src_path,det_path for i,_ in dir_walk('/home'): print(i) 主要有几个疑问,大家帮忙试着解答下哈:
- 代码的执行效率如何,递归时使用 yield 会不会没有发挥 yield 的作用
- yield from 和递归一起使用感觉怪怪的,这是我试出来的,这样写竟然可以用,谁帮忙解释下怎么的语法啊
- 为了让方法可以同时满足我上面说的两种功能,所以加的第二个参数默认为 None,然后方法里一些判断,当然这样就降低了代码的效率,有更好的解决办法吗?
