首页 > 文章列表 > python多线程处理大量文件数据

python多线程处理大量文件数据

python多线程 多线程处理文件
117 2022-08-07

在python中,我们会遇到处理大量文件数据的时候。如果我们用for循环顺序处理,处理文件数据效率额很低,这时我们就可以使用我们的多线程来处理多个超大的文件数据。

第一步:导入import threading 模块

import threading

第二步:使用多线程可以同时打开并运行多个数据

#! /usr/bin/env python
#encoding=utf-8
 
import threading
import time
from Queue import Queue
 
def readFile():
    file_object = open('/opt/dev/python/list.dat')
    global queue
    for line in file_object:                    
        queue.put(line)
 
class Consumer(threading.Thread):
    def run(self):
        global queue
        while queue.qsize() > 0:
            msg = self.name + '消费了 '+queue.get()
            print msg
            time.sleep(0.01)
 
queue = Queue()
def main():
    readFile()
    for i in range(5):
        c = Consumer()
        c.start()
 
if __name__ == '__main__':
    main()

(推荐操作系统:windows7系统、Python 3.9.1,DELL G3电脑。)