python多线程下载小说章节重复_Python 多线程搜索txt文件的内容,并写入搜到的内容(Lock)方法...

Python多线程搜索文件内容实现
该博客展示了使用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")

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值