python 遞歸遍歷文件夾,並打印滿足條件的文件路徑


題目:利用協程來遍歷目錄下,所有子文件及子文件夾下的文件是否含有某個字段值,並打印滿足條件的文件的絕對路徑。

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

#grep -rl "python"  D:\devtools\workspace\python\aaa

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.簡化了程序的復雜度
缺點:不具有可擴展性(內部耦合度太高)

具體應用場景:那些長期不需要怎么變化的軟件。如系統


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM