码迷,mamicode.com
首页 > 编程语言 > 详细

python/面向过程的编程思想及举例

时间:2017-04-24 19:44:30      阅读:242      评论:0      收藏:0      [点我收藏+]

标签:sea   包含   目录   x11   title   func   next   tar   tac   

python基础——面向过程的编程思想及举例

面向过程的编程思想

1、面向过程的编程思想及举例

 

写程序时:

 

要先想功能,分步实现

 

2、 os模块中walk输出目录中文件路径

 

os.walk() 方法用于通过在目录树中游走输出在目录中的文件名,向上或者向下。

技术分享

技术分享

技术分享

 

Send可以传多个值,但是必须是元组类型

 

面向过程的编程思想

像流水线,代码简洁,体系结构

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
实现对一个目录下面(包含子目录下面)有一行包含过滤字符串就输出其文件名的绝对路径
  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")

 

简单方法实现上面程序 

1
2
3
4
5
6
7
8
9
10
11
12
13
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")

python/面向过程的编程思想及举例

标签:sea   包含   目录   x11   title   func   next   tar   tac   

原文地址:http://www.cnblogs.com/guobaoyuan/p/6758461.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!