python多線程分塊讀取文件
更新時間:2019年08月29日 09:57:31 作者:美如畫是我
這篇文章主要為大家詳細介紹了python多線程分塊讀取文件,具有一定的參考價值,感興趣的小伙伴們可以參考一下
本文實例為大家分享了python多線程分塊讀取文件的具體代碼,供大家參考,具體內容如下
# _*_coding:utf-8_*_
import time, threading, ConfigParser
'''
Reader類,繼承threading.Thread
@__init__方法初始化
@run方法實現(xiàn)了讀文件的操作
'''
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()
'''
對文件進行分塊,文件塊的數(shù)量和線程數(shù)量一致
'''
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')
#線程數(shù)量
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中根據(jù)時間自動創(chuàng)建文件夾的代碼實現(xiàn)
這篇文章主要介紹了Python中根據(jù)時間自動創(chuàng)建文件夾的代碼實現(xiàn),這樣的話給工作帶來極大的便利,方便桌面文件按時間存放,具體實例代碼跟隨小編一起看看吧2021-10-10
基于Python中isfile函數(shù)和isdir函數(shù)使用詳解
今天小編就為大家分享一篇基于Python中isfile函數(shù)和isdir函數(shù)使用詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-11-11
Python?Concurrent?Futures解鎖并行化編程的魔法示例
Python的concurrent.futures模塊為并行化編程提供了強大的工具,使得開發(fā)者能夠輕松地利用多核心和異步執(zhí)行的能力,本文將深入探討concurrent.futures的各個方面,從基礎概念到高級用法,為讀者提供全面的了解和實用的示例代碼2023-12-12
解決python3 json數(shù)據(jù)包含中文的讀寫問題
這篇文章主要介紹了解決python3 json數(shù)據(jù)包含中文的讀寫問題,需要的朋友可以參考下2021-05-05

