一种节省内存读取文档的方法

634 阅读 · 2020年4月19日 13:23 更新 · 作者:clannadhh


import sys
 
def read_file(fpath): 
   BLOCK_SIZE = 1024 
   with open(fpath, 'rb') as f: 
       while True: 
           block = f.read(BLOCK_SIZE) 
           if block: 
               yield block 
           else:
               return
r = read_file(r'C:\Users\Administrator\Desktop\ppp.pdf')
while True:
    try:
        print(next(r))
    except StopIteration:
        sys.exit()