美文网首页
python读取大文件处理时使用多线程

python读取大文件处理时使用多线程

作者: 小猪佩奇的王子 | 来源:发表于2019-10-11 14:17 被阅读0次

如果有个很大的文件,几十G?,需要每次读取一部分,处理后再读取剩余部分。
with open as f已经从内部处理难点,使用for line in f以迭代器的形式每次读取一行,不会有内存问题。

下面程序的思路是用一个列表存放读取到的数据,达到长度后就开始处理,处理完就清空列表,继续执行


def open_file_with_thread():

    def do_test(li, lists):
        time.sleep(3)
        print(lists, '->>')

    s = time.time()
    lists = [] #创建一个空列表,达到每个长度后,就清空
    threads =[] #根据lists来创建线程,执行完后清空
    with open('./password.txt', 'r') as f:
        for x in f:
            if len(lists) < 3:
                lists.append(x)
            else:
                for y in range(2):
                    t = threading.Thread(target=do_test, args=(y, lists))
                    t.start()
                    threads.append(t)
                    
                for th in threads:
                    th.join()
                lists = []
                threads=[]
        e = time.time()
        print(e-s)

open_file_with_thread()

相关文章

网友评论

      本文标题:python读取大文件处理时使用多线程

      本文链接:https://www.haomeiwen.com/subject/egbtmctx.html