这篇文章将为大家详细讲解有关python多线程如何分块读取文件,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。
具体内容如下
# _*_coding:utf-8_*_
import time, threading, ConfigParser
'''
Reader类,继承threading.Thread
@__init__方法初始化
@run方法实现了读文件的操作
'''
class Reader(threading.Thread):
def __init__(self, file_name, start_pos, end_pos):
super(Reader, self).__init__()
self.file_name = file_name
self.start_pos = start_pos
self.end_pos = end_pos
def run(self):
fd = open(self.file_name, 'r')
'''
该if块主要判断分块后的文件块的首位置是不是行首,
是行首的话,不做处理
否则,将文件块的首位置定位到下一行的行首
'''
if self.start_pos != 0:
fd.seek(self.start_pos-1)
if fd.read(1) != '\n':
line = fd.readline()
self.start_pos = fd.tell()
fd.seek(self.start_pos)
'''
对该文件块进行处理
'''
while (self.start_pos <= self.end_pos):
line = fd.readline()
'''
do somthing
'''
self.start_pos = fd.tell()
'''
对文件进行分块,文件块的数量和线程数量一致
'''
class Partition(object):
def __init__(self, file_name, thread_num):
self.file_name = file_name
self.block_num = thread_num
def part(self):
fd = open(self.file_name, 'r')
fd.seek(0, 2)
pos_list = []
file_size = fd.tell()
block_size = file_size/self.block_num
start_pos = 0
for i in range(self.block_num):
if i == self.block_num-1:
end_pos = file_size-1
pos_list.append((start_pos, end_pos))
break
end_pos = start_pos+block_size-1
if end_pos >= file_size:
end_pos = file_size-1
if start_pos >= file_size:
break
pos_list.append((start_pos, end_pos))
start_pos = end_pos+1
fd.close()
return pos_list
if __name__ == '__main__':
'''
读取配置文件
'''
config = ConfigParser.ConfigParser()
config.readfp(open('conf.ini'))
#文件名
file_name = config.get('info', 'fileName')
#线程数量
thread_num = int(config.get('info', 'threadNum'))
#起始时间
start_time = time.clock()
p = Partition(file_name, thread_num)
t = []
pos = p.part()
#生成线程
for i in range(thread_num):
t.append(Reader(file_name, *pos[i]))
#开启线程
for i in range(thread_num):
t[i].start()
for i in range(thread_num):
t[i].join()
#结束时间
end_time = time.clock()
print "Cost time is %f" % (end_time - start_time)
关于“python多线程如何分块读取文件”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。