这里会使用yield生成自定义可迭代对象, 即generator, 每一个带有yield的函数就是一个generator。
def read_in_block(file_path):
BLOCK_SIZE = 1024
with open(file_path, "r") as f:
while True:
block = f.read(BLOCK_SIZE) # 每次读取固定长度到内存缓冲区
if block:
yield block
else:
return # 如果读取到文件末尾,则退出
def test3():
file_path = "/tmp/test.log"
for block in read_in_block(file_path):
print(block)