廢話不多說(shuō),直接上代碼吧!
import threading import os class Find(threading.Thread): #搜索數(shù)據(jù)的線程類 def __init__(self,datalist,startIndex,endIndex,searchstr,savefile): #datalist要搜索的內(nèi)容列表,startIndex列表搜索范圍的開(kāi)始下標(biāo),searchstr要搜索的內(nèi)容 threading.Thread.__init__(self) self.datalist=datalist #要搜索的數(shù)據(jù)的內(nèi)存地址 self.startIndex=startIndex #開(kāi)始的索引 self.endIndex=endIndex #結(jié)束的索引 self.seachstr=searchstr #需要搜索的數(shù)據(jù) 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="") #搜索數(shù)據(jù) self.findlist.append(line) global mutex #多線程共享全局變量(全局鎖) with mutex: #獲取鎖(自動(dòng)釋放鎖) for line in self.findlist: self.savefile.write(line.encode("gbk")) mutex=threading.Lock() #創(chuàng)建一個(gè)鎖 savefile=open("c:\\zhaodao.txt","wb") #搜索到的內(nèi)容寫入該文件 path = "C:\\data1.txt" #要搜索的文件 file = open(path, "rb") datalist = file.readlines() # 全部讀入內(nèi)存 lines=len(datalist) #所有的行數(shù) searchstr=input("輸入要查詢的數(shù)據(jù)") N=10 #開(kāi)啟10個(gè)線程 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 數(shù)據(jù)切割 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) #最后的線程搜索剩下的尾數(shù) mylastthd.start() threadlist.append(mylastthd) #添加到線程列表 for thd in threadlist: #遍歷線程列表 thd.join() print("finish")
以上這篇Python 多線程搜索txt文件的內(nèi)容,并寫入搜到的內(nèi)容(Lock)方法就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

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