最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python 多線程搜索txt文件的內(nèi)容,并寫入搜到的內(nèi)容(Lock)方法

 更新時間:2019年08月23日 16:44:57   作者:houyanhua1  
今天小編就為大家分享一篇Python 多線程搜索txt文件的內(nèi)容,并寫入搜到的內(nèi)容(Lock)方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧

廢話不多說,直接上代碼吧!

import threading
import os
 
class Find(threading.Thread): #搜索數(shù)據(jù)的線程類
 def __init__(self,datalist,startIndex,endIndex,searchstr,savefile): #datalist要搜索的內(nèi)容列表,startIndex列表搜索范圍的開始下標,searchstr要搜索的內(nèi)容
  threading.Thread.__init__(self)
  self.datalist=datalist #要搜索的數(shù)據(jù)的內(nèi)存地址
  self.startIndex=startIndex #開始的索引
  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: #獲取鎖(自動釋放鎖)
 		for line in self.findlist:
 			self.savefile.write(line.encode("gbk"))
  	
 
mutex=threading.Lock() #創(chuàng)建一個鎖
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 #開啟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 數(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)方法就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論

临清市| 绥化市| 将乐县| 昌乐县| 泰州市| 通海县| 滁州市| 祁连县| 泗水县| 原阳县| 蕲春县| 林甸县| 南京市| 肥东县| 南江县| 锦州市| 独山县| 石棉县| 孟连| 龙海市| 梅河口市| 吴旗县| 海门市| 大姚县| 兰州市| 祁阳县| 永吉县| 丹棱县| 二连浩特市| 应用必备| 清水县| 永德县| 明光市| 武功县| 六安市| 泽普县| 花莲市| 新闻| 镇雄县| 新安县| 虎林市|