廢話不多說,直接上代碼吧!
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)方法就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
