python基础——面向过程的编程思想及举例
面向过程的编程思想
1、面向过程的编程思想及举例
写程序时:
要先想功能,分步实现
2、 os模块中walk输出目录中文件路径
os.walk() 方法用于通过在目录树中游走输出在目录中的文件名,向上或者向下。
Send可以传多个值,但是必须是元组类型
面向过程的编程思想
像流水线,代码简洁,体系结构
实现对一个目录下面(包含子目录下面)有一行包含过滤字符串就输出其文件名的绝对路径 C:\python_fullstack_wen\day24\wen """ import time,os #定义 def init(func): "装饰器" def wrapper(*args,**kwargs): res=func(*args,**kwargs) next(res) return res return wrapper @init def search(target): "找到目录下所有文件名的绝对路径" while True: dir_path=yield g=os.walk(dir_path) for i in g: for j in i[-1]: file_path="%s\\%s"%(i[0],j) target.send(file_path) @init def opener(target): "打开文件,返回文件句柄" while True: file_path=yield with open(file_path) as f: target.send((file_path,f)) @init def cat(target): "查看文件,返回每行内容" while True: file_path,f=yield for line in f: target.send((file_path,line)) @init def grep(pattern,target): "过滤这行,如果符合返回文件路径" while True: file_path,line=yield if pattern in line: target.send(file_path) @init def printer(): "打印" while True: file_path=yield print(file_path) #调用 g=search(opener(cat(grep("wenyanjie",printer())))) g.send("C:\python_fullstack_wen\day24\wen")
简单方法实现上面程序
import os def search(dir_name, partten): g = os.walk(dir_name) for i in g: for j in i[-1]: file_path = i[0] + "\\" +j with open(file_path) as f: for line in f: if partten in line: print(file_path) search("c:\\test", "python")