Python Basics-process-oriented programming ideas and examples
Process-oriented programming ideas
1, process-oriented programming ideas and examples
When writing a program:
To think about features first, step through the implementation of
2. File path in walk output directory in OS module
The Os.walk () method is used to go through the directory tree to output the file name in the directory, up or down.
Send can pass multiple values, but must be a tuple type
Process-oriented programming ideas
Like pipelining, code simplicity, architecture
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455 |
实现对一个目录下面(包含子目录下面)有一行包含过滤字符串就输出其文件名的绝对路径
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"
)
|
Simple way to implement the above program
12345678910111213 |
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/process-oriented programming ideas and examples