Python 多线程搜索txt文件的内容,并写入搜到的内容(Lock)方法
作者:houyanhua1 时间:2021-01-15 12:48:34
废话不多说,直接上代码吧!
import threading
import os
class Find(threading.Thread): #搜索数据的线程类
def __init__(self,datalist,startIndex,endIndex,searchstr,savefile): #datalist要搜索的内容列表,startIndex列表搜索范围的开始下标,searchstr要搜索的内容
threading.Thread.__init__(self)
self.datalist=datalist #要搜索的数据的内存地址
self.startIndex=startIndex #开始的索引
self.endIndex=endIndex #结束的索引
self.seachstr=searchstr #需要搜索的数据
self.savefile=savefile
def run(self):
self.findlist=[]
for i in range(self.startIndex,self.endIndex):
line=self.datalist[i].decode("gbk","ignore") #读取一行
if line.find(self.seachstr)!=-1:
print(self.getName(),line,end="") #搜索数据
self.findlist.append(line)
global mutex #多线程共享全局变量(全局锁)
with mutex: #获取锁(自动释放锁)
for line in self.findlist:
self.savefile.write(line.encode("gbk"))
mutex=threading.Lock() #创建一个锁
savefile=open("c:\\zhaodao.txt","wb") #搜索到的内容写入该文件
path = "C:\\data1.txt" #要搜索的文件
file = open(path, "rb")
datalist = file.readlines() # 全部读入内存
lines=len(datalist) #所有的行数
searchstr=input("输入要查询的数据")
N=10 #开启10个线程
threadlist=[] #线程列表
# 97 9 0-1000000 1000000-2000000 2000000-3000000
for i in range(0,N-1): #0,1,2,3,4,5,6,7,8 数据切割
mythd= Find(datalist,i*(lines//(N-1)) , (i+1)*(lines//(N-1)),searchstr,savefile) # //表示整除
mythd.start()
threadlist.append(mythd) #添加到线程列表
#97 = 97//10*10=90
mylastthd= Find(datalist,lines//(N-1)*(N-1),lines,searchstr,savefile) #最后的线程搜索剩下的尾数
mylastthd.start()
threadlist.append(mylastthd) #添加到线程列表
for thd in threadlist: #遍历线程列表
thd.join()
print("finish")
来源:https://blog.csdn.net/houyanhua1/article/details/78250843
标签:Python,多线程,搜索,txt
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
如何使用FSO搜索硬盘文件
2007-09-27 12:59:00
PHP数据库表操作的封装类及用法实例详解
2023-11-12 07:41:23
使用matplotlib绘制并排柱状图的实战案例
2022-04-06 01:22:25
![](https://img.aspxhome.com/file/2023/7/81627_0s.png)
OL IE Bug
2009-09-09 16:25:00
SQL语句操作主从关系表
2011-06-19 13:19:05
python 从远程服务器下载东西的代码
2023-01-23 11:00:55
Oracle数据库游标使用大全
2008-03-04 18:24:00
ASP 使用jqGrid实现读写删的代码(json)
2010-03-07 17:26:00
将以用户为中心的设计嵌入产品设计和开发流程
2009-08-11 14:27:00
![](https://img.aspxhome.com/file/UploadPic/20098/11/web-design-process-29s.png)
如何解决SQLServer占内存过多的问题
2008-12-18 15:01:00
WEB设计经验-来自Microsoft
2008-05-15 07:30:00
Golang异常处理之defer,panic,recover的使用详解
2023-08-06 14:20:09
python tkinter制作用户登录界面的简单实现
2021-01-07 06:00:09
![](https://img.aspxhome.com/file/2023/4/85344_0s.jpg)
关于网站地图
2011-01-06 12:14:00
![](https://img.aspxhome.com/file/UploadPic/20111/6/116-64s.jpg)
Python实现学生管理系统的代码(JSON模块)
2022-01-02 07:54:42
![](https://img.aspxhome.com/file/2023/6/81626_0s.png)
python获取百度热榜链接的实例方法
2022-10-02 23:10:01
![](https://img.aspxhome.com/file/2023/6/82936_0s.png)
Python anaconda安装库命令详解
2023-01-31 16:36:36
![](https://img.aspxhome.com/file/2023/7/85037_0s.png)
用Mimer Validator检查SQL查询
2009-04-24 11:59:00
Python函数参数定义及传递方式解析
2021-10-19 21:28:25
PHP将amr音频文件转换为mp3格式的操作细节
2023-06-15 22:20:35