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)

 

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
多线程读写大文件可以提高文件读写的效率,常用的方法有两种:分块读写和多线程读写。 1. 分块读写 分块读写是将大文件划分为多个块,每个线程读取一个块的数据进行处理,在处理完后将结果写入文件。这种方法的好处是可以充分利用多个线程,但需要注意的是需要保证多个线程读写的块大小要相同。 示例代码如下: ```python import os import threading def process_block(block): # 处理块的函数 pass def read_file(file_path, block_size): file_size = os.path.getsize(file_path) num_blocks = (file_size + block_size - 1) // block_size # 计算块数 threads = [] with open(file_path, 'rb') as f: for i in range(num_blocks): start = i * block_size end = min(start + block_size, file_size) block = f.read(end - start) t = threading.Thread(target=process_block, args=(block,)) threads.append(t) t.start() for t in threads: t.join() if __name__ == '__main__': file_path = 'large_file.txt' block_size = 1024 * 1024 # 1MB read_file(file_path, block_size) ``` 2. 多线程读写 多线程读写是将文件分成多个部分,每个线程负责处理一个部分,可以采用线程池的方式来管理多个线程。这种方法的好处是可以充分利用 CPU 和 IO 资源,但需要注意的是需要保证多个线程读写的部分大小要相同。 示例代码如下: ```python import os import concurrent.futures def process_chunk(chunk): # 处理部分的函数 pass def read_file(file_path, num_threads): file_size = os.path.getsize(file_path) chunk_size = (file_size + num_threads - 1) // num_threads # 计算部分大小 with open(file_path, 'rb') as f: with concurrent.futures.ThreadPoolExecutor(max_workers=num_threads) as executor: futures = [] for i in range(num_threads): start = i * chunk_size end = min(start + chunk_size, file_size) chunk = f.read(end - start) futures.append(executor.submit(process_chunk, chunk)) for future in concurrent.futures.as_completed(futures): result = future.result() if __name__ == '__main__': file_path = 'large_file.txt' num_threads = 4 read_file(file_path, num_threads) ``` 在上面的示例代码中,我们使用了 Python 的 `concurrent.futures` 模块来实现多线程读写。首先将大文件分成多个部分,然后使用线程池的方式来管理多个线程,每个线程负责处理一个部分,从而充分利用 CPU 和 IO 资源。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值