python多进程分块读取文件

本文介绍了一个使用Python多进程实现的大文件分块读取方法。通过将文件读取任务分配给多个进程并行处理,有效提高了文件读取效率。每个进程负责读取文件的一部分,并将数据写入到临时文件中。

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

# -*- coding: GBK -*-
# filename: multiprocessreadfile.py

import urlparse
import datetime
import os
from multiprocessing import Process,Queue,Array,RLock

"""
多进程分块读取文件
"""

WORKERS = 4
BLOCKSIZE = 100000000 #字节,接近100MB
FILE_SIZE = 0

def getFilesize(file):
    """
        获取要读取文件的大小
    """
    global FILE_SIZE
    fstream = open(file,'r')
    fstream.seek(0,os.SEEK_END)
    FILE_SIZE = fstream.tell()
    fstream.close()

def process_found(pid,array,file,rlock):
    global FILE_SIZE
    global JOB
    global PREFIX
    """
        进程处理
        Args:
            pid:进程编号
            array:进程间共享队列,用于标记各进程所读的文件块结束位置
            file:所读文件名称
        各个进程先从array中获取当前最大的值为起始位置startpossition
        结束的位置endpossition (startpossition+BLOCKSIZE) if (startpossition+BLOCKSIZE)<FILE_SIZE else FILE_SIZE
        if startpossition==FILE_SIZE则进程结束
        if startpossition==0则从0开始读取
        if startpossition!=0为防止行被block截断的情况,先读一行不处理,从下一行开始正式处理
        if 当前位置 <=endpossition 就readline
        否则越过边界,就从新查找array中的最大值
    """
    fstream = open(file,'r')
    
    while True:
        rlock.acquire()
        print 'pid%s'%pid,','.join([str(v) for v in array])
        startpossition = max(array)            
        endpossition = array[pid] = (startpossition+BLOCKSIZE) if (startpossition+BLOCKSIZE)<FILE_SIZE else FILE_SIZE
        rlock.release()
        
        if startpossition == FILE_SIZE:#end of the file
            print 'pid%s end'%(pid)
            break
        elif startpossition !=0:
            fstream.seek(startpossition)
            fstream.readline()
        pos = ss = fstream.tell()
        ostream = open('/data/download/tmp_pid'+str(pid)+'_jobs'+str(endpossition),'w')
        while pos<endpossition:
            #处理line
            line = fstream.readline()                        
            ostream.write(line)
            pos = fstream.tell()

        print 'pid:%s,startposition:%s,endposition:%s,pos:%s'%(pid,ss,pos,pos)
        ostream.flush()
        ostream.close()
        ee = fstream.tell()        

    fstream.close()

def main():
    global FILE_SIZE
    print datetime.datetime.now().strftime("%Y/%d/%m %H:%M:%S") 
    
#    file = "/data/pds/download/scmcc_log/tmp_format_2011004.log"
    file = "zdmm1_10.txt"
    getFilesize(file)
    print FILE_SIZE
    
    rlock = RLock()
    array = Array('l',WORKERS,lock=rlock)
    threads=[]
    for i in range(WORKERS):
        p=Process(target=process_found, args=[i,array,file,rlock])
        threads.append(p)

    for i in range(WORKERS):
        threads[i].start()
    
    for i in range(WORKERS):
        threads[i].join()

    print datetime.datetime.now().strftime("%Y/%d/%m %H:%M:%S") 

if __name__ == '__main__':
    main()


点击打开链接

### 使用 Python 实现多进程读取文件Python 中,`multiprocessing` 库提供了创建和管理子进程的功能。通过该库可以轻松实现多进程并行处理任务,比如同时读取多个文件分块读取单个大文件。 以下是基于 `multiprocessing` 的一个多进程文件读取示例: #### 示例代码 ```python import os from multiprocessing import Process, Queue def read_file(file_path, queue): """ 子进程函数:用于读取指定文件的内容 """ try: with open(file_path, 'r', encoding='utf-8') as file: content = file.read() queue.put((file_path, content)) except Exception as e: queue.put((file_path, str(e))) if __name__ == "__main__": files_to_read = ['file1.txt', 'file2.txt', 'file3.txt'] # 待读取文件列表 processes = [] result_queue = Queue() # 创建子进程来读取每个文件 for file in files_to_read: process = Process(target=read_file, args=(file, result_queue)) processes.append(process) process.start() # 收集所有子进程的结果 results = {} while len(results) < len(files_to_read): file_path, content = result_queue.get() results[file_path] = content # 等待所有子进程结束 for process in processes: process.join() # 输出结果 for file_path, content in results.items(): print(f"File {file_path} Content:\n{content[:100]}...") # 打印前100字符作为示例 ``` 上述代码展示了如何使用 `Process` 和 `Queue` 来实现多进程并发读取文件[^1]。 - **`read_file` 函数** 是子进程中执行的任务,负责打开并读取文件内容。 - **`result_queue`** 被用来存储各子进程返回的数据。 - 主程序会启动若干子进程分别读取不同文件,并最终收集这些数据。 如果目标是读取一个非常大的单一文件,则可以通过分割文件的方式分配给不同的进程进行处理[^3]^: #### 单一大文件分块读取示例 ```python from multiprocessing import Pool CHUNK_SIZE = 1024 * 1024 # 每次读取1MB大小的数据块 def read_chunk(start_byte, end_byte, file_path): """ 读取文件中的特定字节范围 """ with open(file_path, 'rb') as f: f.seek(start_byte) data = f.read(end_byte - start_byte) return data.decode('utf-8') def get_chunks(file_size, chunk_size): """ 将文件分成多个块 """ chunks = [(i, min(i + chunk_size, file_size)) for i in range(0, file_size, chunk_size)] return chunks if __name__ == '__main__': large_file = 'large_file.txt' file_size = os.path.getsize(large_file) pool = Pool() # 初始化进程池 chunks = get_chunks(file_size, CHUNK_SIZE) results = [ pool.apply_async(read_chunk, (start, end, large_file)) for start, end in chunks ] all_data = ''.join(result.get() for result in results if result is not None) pool.close() pool.join() print("Total characters:", len(all_data)) ``` 此代码片段展示了一个更复杂的场景——将大型文件划分为固定大小的小块,并由多个进程共同完成其解析工作[^5]。 --- ### 性能对比:多线程 vs 多进程 需要注意的是,在 I/O 密集型操作(如文件读写)上,多线程可能表现得更好;而在 CPU 密集型计算方面,由于 GIL (Global Interpreter Lock),通常推荐采用多进程方式[^2]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值