使用文本文件,我可以写出以下内容:
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中迭代二进制文件的惯用方法是什么?
iter
调用没有起作用。在这种情况下,编写迭代器可能也是我会做的事情,除非在交互式提示符中工作。 - liorif.read
的事实。 - Jason Bakerfunctools.partial(f.read, numBytes)
可以替代lambda
的作用。 - Jochen Ritzelb''
。在 Python 3 中,字符串文字是 Unicode 对象;而在 Python 2 中可以通过from __future__ import unicode_literals
导入后,也可以使用 Unicode 字符串文字。 - George V. Reilly