Python 多线程搜索txt文件的内容,并写入搜到的内容(Lock)方法

yipeiwu_com5年前Python基础

废话不多说,直接上代码吧!

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")

以上这篇Python 多线程搜索txt文件的内容,并写入搜到的内容(Lock)方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python的函数嵌套的使用方法

例子:复制代码 代码如下:def re_escape(fn):    def arg_escaped(this, *args):  &n...

使用pandas将numpy中的数组数据保存到csv文件的方法

使用pandas将numpy中的数组数据保存到csv文件的方法

接触pandas之后感觉它的很多功能似乎跟numpy有一定的重复,尤其是各种运算。不过,简单的了解之后发现在数据管理上pandas有着更为丰富的管理方式,其中一个很大的优点就是多出了对数...

python ftplib模块使用代码实例

这篇文章主要介绍了python ftplib模块使用代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 Python中默认安装的f...

Python 调用DLL操作抄表机

# -*- coding: GBK -*- from ctypes import * dll = windll.LoadLibrary('JBA188.dll') a = dll.tes...

利用Python实现微信找房机器人实例教程

利用Python实现微信找房机器人实例教程

目的 两年前曾为了租房做过一个找房机器人 「爬取豆瓣租房并定时推送到微信」,维护一段时间后就荒废了。 当时因为代码比较简单一直没开源,现在想想说不定开源后也能帮助一些同学更好的找到租房信...