python 递归遍历文件夹,并打印满足条件的文件路径实例
作者:nolimite 时间:2023-08-07 07:22:48
题目:利用协程来遍历目录下,所有子文件及子文件夹下的文件是否含有某个字段值,并打印满足条件的文件的绝对路径。
#!/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.简化了程序的复杂度
缺点:不具有可扩展性(内部耦合度太高)
具体应用场景:那些长期不需要怎么变化的软件。如系统
来源:http://www.cnblogs.com/yangzhenwei123/p/6759228.html
标签:python,递归,遍历,文件夹,文件路径
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
python操作MySQL数据库的方法分享
2024-01-13 16:11:54
CSS3属性box-shadow图层阴影效果使用教程
2010-05-16 14:54:00
![](https://img.aspxhome.com/file/UploadPic/20105/16/01-89s.jpg)
解决Tensorflow安装成功,但在导入时报错的问题
2022-03-05 18:39:27
js运算精度丢失的2个解决方法
2024-04-10 10:38:02
![](https://img.aspxhome.com/file/2023/5/137065_0s.png)
交互设计实用指南系列(6) –标签明晰、有效
2010-01-21 12:39:00
![](https://img.aspxhome.com/file/UploadPic/20101/21/32-66s.jpg)
PHP删除数组中指定值的元素常用方法实例分析【4种方法】
2024-06-05 09:51:58
mysql按照时间分组查询的语句
2024-01-20 05:39:24
![](https://img.aspxhome.com/file/2023/1/105481_0s.png)
golang的序列化与反序列化的几种方式
2024-05-22 10:11:53
使用pytorch实现可视化中间层的结果
2022-12-11 03:30:24
![](https://img.aspxhome.com/file/2023/3/102723_0s.jpg)
MySQL中的binlog相关命令和恢复技巧
2024-01-22 20:42:08
python imutils包基本概念及使用
2023-10-20 21:38:09
![](https://img.aspxhome.com/file/2023/6/131256_0s.png)
go zero微服务实战性能优化极致秒杀
2023-06-17 03:45:30
![](https://img.aspxhome.com/file/2023/4/86304_0s.jpg)
pandas loc iloc ix用法详细分析
2021-08-31 20:16:53
javascript中直接写php代码的方法
2024-05-02 16:27:46
彻底理解Python list切片原理
2023-10-19 03:34:43
python神经网络编程实现手写数字识别
2021-08-31 16:08:14
![](https://img.aspxhome.com/file/2023/0/133330_0s.jpg)
Python linecache.getline()读取文件中特定一行的脚本
2023-03-09 13:18:05
![](https://img.aspxhome.com/file/2023/5/67725_0s.gif)
python 同时读取多个文件的例子
2022-06-27 03:56:50
python-图片流传输的思路及示例(url转换二维码)
2021-06-18 14:48:44
Oracle在PL/SQL中嵌入SQL语句
2024-01-19 03:06:03