多线程分块(按字节进行)读取多个文件

该博客介绍了一种使用多线程按字节分块读取多个文件的方法。首先统计每个文件的大小,然后根据线程数量分配文件块,最后通过ThreadPoolExecutor并行读取和处理文件内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

"""
多线程分块(按字节进行)读取多个文件
1、统计文件的大小
2、根据线程数对文件大小进行分块
3、多线程根据分块行进行读取文件
"""
import os
from concurrent.futures.thread import ThreadPoolExecutor
import time


def size_file(file):
    """
    统计文件大小(字节)
    :return:
    """
    count = os.path.getsize(file)
    return count


def part_size_file(file, thread_num):
    """
    根据文件字节数对文件按字节大小进行分块
    :return:
    """
    size = size_file(file)
    num = size // thread_num  # 计算每块的行数
    i = 0
    tt = []  # 存放分块的行数
    t = 0
    while i < thread_num - 1:
        tt.append((t + i, (i + 1) * num))
        t = (i + 1) * num
        i += 1
    tt.append((t + 1, size))
    return tt


def Read_file(args):
    """
    分块读取文件
    :param tt:
    :param file:
    :return:
    """
    start_pos = args[0][0]
    end_pos = args[0][1]
    print(args[0][0], args[0][1])
    with open(args[1], "r", encoding="gbk", errors="ignore") as f:
        if start_pos != 0:
            f.seek(args[0][0] - 1)
            if f.read(1) != '\n':
                line = f.readline()
                start_pos = f.tell()
        f.seek(args[0][0])
        # print(start_pos)
        while (start_pos <= end_pos):
            line = f.readline()
            # print(line)
            '''
            do somthing
            '''
            start_pos = f.tell()
    f.close()


def thread_pool_readfile(file):
    """
    多线程分块读取文件
    :return:
    """
    thread_num = 4
    tt = part_size_file(file, thread_num=thread_num)
    p = ThreadPoolExecutor(thread_num)
    for i in range(len(tt)):
        p.submit(Read_file, args=(tt[i], file))
        # time.sleep(2)
    p.submit(True)


if __name__ == '__main__':
    file = r"E:\数据处理\资源树换新数据源\v_uplink.txt"
    start = time.clock()
    count = size_file(file)
    thread_pool_readfile(file)
    end = time.clock()
    print("Cost time  %s seconds" % (end - start))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值