
在python中,我们会遇到处理大量文件数据的时候。如果我们用for循环顺序处理,处理文件数据效率额很低,这时我们就可以使用我们的多线程来处理多个超大的文件数据。
第一步:导入import threading 模块
第二步:使用多线程可以同时打开并运行多个数据
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | #! /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()
|
以上就是用python多线程处理大量数据的演示代码,如果有需要处理大量文件的小伙伴,可以尝试使用多线程,会方便很多哦~
(推荐操作系统:windows7系统、Python 3.9.1,DELL G3电脑。)