python 递归遍历文件夹,并打印满足条件的文件路径

题目:利用协程来遍历目录下,所有子文件及子文件夹下的文件是否含有某个字段值,并打印满足条件的文件的绝对路径。

#!/user/bin/env python
# -*- coding:utf-8 -*-

#grep -rl "python"  D:devtoolsworkspacepythonaaa

import os

def init(func):
    def wrapper(*args,**kwargs):
        res=func(*args,**kwargs)
        res.send(None)
        return res
    return wrapper

@init
def search(target):
    '找到文件的绝对路径'
    while True:
        dir_name=yield
        g=os.walk(dir_name)
        for i in g:
            for j in i[-1]:
                file_path="%s\%s"%(i[0],j)
                target.send(file_path)
@init
def get_file_handle(target):
    '获取文件句柄'
    while True:
        file_path=yield
        with open(file_path) as f:
            target.send((file_path,f))

@init
def cat_file(target):
    '读取文件'
    while True:
        file_path,f=yield
        for line in f:
            target.send((file_path,line))

@init
def printer(pattern):
    '打印满足过滤条件的文件'
    s=set()
    while True:
        file_path,line=yield
        if pattern in line:
            if file_path not in s:
                print(file_path)
            s.add(file_path)


g=search(get_file_handle(cat_file(printer("python"))))
g.send("D:\devtools\workspace\python\aaa")

使用装饰器以后,无需再每次执行.send(None),形参target接收的是一个生成器。

整个编程采用了面向过程的思路。
面向过程需要把整个流程设计出来。
其好处就是:a.体系结构更加清晰;b.简化了程序的复杂度
缺点:不具有可扩展性(内部耦合度太高)

具体应用场景:那些长期不需要怎么变化的软件。如系统

原文地址:https://www.cnblogs.com/yangzhenwei123/p/6759228.html