python多线程分块读取文件

yipeiwu_com5年前Python基础

本文实例为大家分享了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设计】。

相关文章

Python 将RGB图像转换为Pytho灰度图像的实例

问题: 我正尝试使用matplotlib读取RGB图像并将其转换为灰度。 在matlab中,我使用这个: img = rgb2gray(imread('image.png'));...

Python使用selenium + headless chrome获取网页内容的方法示例

使用python写爬虫时,优选selenium,由于PhantomJS因内部原因已经停止更新,最新版的selenium已经使用headless chrome替换掉了PhantomJS,所...

Python将视频或者动态图gif逐帧保存为图片的方法

本文是基于opencv将视频和动态图gif保存为图像帧。可以根据输入视频格式的不同,修改第21行。        对动图的处理...

10种检测Python程序运行时间、CPU和内存占用的方法

10种检测Python程序运行时间、CPU和内存占用的方法

在运行复杂的Python程序时,执行时间会很长,这时也许想提高程序的执行效率。但该怎么做呢? 首先,要有个工具能够检测代码中的瓶颈,例如,找到哪一部分执行时间比较长。接着,就针对这一部分...

Python中除法使用的注意事项

本文实例讲解了Python中除法使用的注意事项,是非常重要的技巧,对于Python程序设计来说有很好的借鉴价值。具体分析如下: 现来看如下示例: def avg(first, *re...