大文件读取 python yield
def read_file(fpath):
BLOCK_SIZE = 1024
with open(fpath, 'rb') as f:
print(f)
while True:
block = f.read(BLOCK_SIZE)
if block:
yield block
else:
return
a = read_file('E:\odoo14\odoo\dlfs_addons.rar')
print(a)
print(next(a))
print(next(a))
print(next(a))
print(next(a))
print(next(a))
![效果图](https://img-blog.csdnimg.cn/20210310094427927.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L1lhbnNrYW5n,size_16,color_FFFFFF,t_70)
### 将文件使用 yield 生成一个可迭代的 generator 对象,然后不停迭代,传输文件流,此操作不会造成超大文件的读取后内存崩溃。