【发布时间】:2011-06-01 18:39:08
【问题描述】:
使用文本文件,我可以这样写:
with open(path, 'r') as file:
for line in file:
# handle the line
这等价于:
with open(path, 'r') as file:
for line in iter(file.readline, ''):
# handle the line
PEP 234 中记录了此成语,但我未能找到二进制文件的类似成语。
使用二进制文件,我可以这样写:
with open(path, 'rb') as file:
while True:
chunk = file.read(1024 * 64)
if not chunk:
break
# handle the chunk
我尝试过与文本文件相同的习语:
def make_read(file, size):
def read():
return file.read(size)
return read
with open(path, 'rb') as file:
for chunk in iter(make_read(file, 1024 * 64), b''):
# handle the chunk
这是在 Python 中迭代二进制文件的惯用方式吗?
【问题讨论】: