1 import os 2 path = ‘H:\\jimmy‘ 3 4 def ne(func): 5 """装饰器功能:为解决生成器需要用next初始化的问题""" 6 def wrapper(*args,**kwargs): 7 res = func(*args,**kwargs) 8 next(res) 9 return res 10 return wrapper 11 12 @ne 13 def search(target): 14 """函数功能为:查询指定的目录中的文件和目录""" 15 while True: 16 dir_name = yield 17 path_g = os.walk(dir_name) 18 for i in path_g: 19 for j in i[-1]: 20 file_path = ‘%s\\%s‘%(i[0],j) 21 target.send(file_path) 22 23 @ne 24 def openner(target): 25 """函数功能为:打开文件""" 26 while True: 27 file_path = yield 28 with open(file_path,mode=‘r‘,encoding=‘utf-8‘) as f: 29 target.send((f,file_path)) 30 31 @ne 32 def cat(target): 33 """函数功能为:得到文件的内容""" 34 while True: 35 f,file_path = yield 36 for line in f : 37 target.send((line,file_path)) 38 39 @ne 40 def filter(partten,target): 41 """函数功能为:过滤打开文件后的指定内容""" 42 while True: 43 line,file_path = yield 44 if partten in line: 45 target.send(file_path) 46 47 @ne 48 def printer(): 49 """函数功能为:打印筛选文件后的文件路径""" 50 while True: 51 file_path = yield 52 print(file_path) 53 54 g = search(openner(cat(filter(‘python‘,printer())))) 55 g.send(path)
原文:http://www.cnblogs.com/mojiexiaolong/p/6700517.html