如果有个很大的文件,几十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()
|