Skip to content

Commit 22ce9c2

Browse files
committed
Create function.py
1 parent c13ab9f commit 22ce9c2

File tree

1 file changed

+15
-0
lines changed

1 file changed

+15
-0
lines changed

function.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
http://www.ibm.com/developerworks/cn/opensource/os-cn-python-yield/
2+
3+
另一个 yield 的例子来源于文件读取如果直接对文件对象调用 read() 方法会导致不可预测的内存占用
4+
好的方法是利用固定长度的缓冲区来不断读取文件内容
5+
通过 yield我们不再需要编写读文件的迭代类就可以轻松实现文件读取
6+
7+
def read_file(fpath):
8+
BLOCK_SIZE = 1024
9+
with open(fpath, 'rb') as f:
10+
while True:
11+
block = f.read(BLOCK_SIZE)
12+
if block:
13+
yield block
14+
else:
15+
return

0 commit comments

Comments
 (0)