今天直接面對了一個很嚴重的問題,生成的一個大的字典,如何打開成了一個問題,因此發覺了一下這個問題:
基本原理:通過不斷取1024KB爲大小的內容,然後通過迭代器yield這個設備讀取無限大的內容。
#coding=utf-8
import os.path
import time
'''
切分成小文件,然後讀取
'''
def read_in_block(filepath):
BLOCK_SIZE = 1024
with open(filepath,'r') as f:
while True:
block = f.read(BLOCK_SIZE)
if block:
yield block
else:
return
if __name__ == '__main__':
path=os.getcwd()
filepath = path + '\pass.txt'
start_time = time.time()
for i in read_in_block(filepath):
print i
end_time = time.time()
print 'Time is ',end_time - start_time