使用文本文件,我可以这样写:
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 中迭代二进制文件的惯用方式吗?
最佳答案
试试:
chunk_size = 4 * 1024 * 1024 # MB
with open('large_file.dat','rb') as f:
for chunk in iter(lambda: f.read(chunk_size), b''):
handle(chunk)
iter
需要一个零参数的函数。
- 一个普通的
f.read
将读取整个文件,因为缺少size
参数; f.read(1024)
表示调用函数并将其返回值(从文件加载的数据)传递给iter
,所以iter
根本没有功能;(lambda:f.read(1234))
是一个接受零参数的函数(lambda
和:
之间没有任何参数)并调用f.read(1234)
.
关于python - 迭代二进制文件的惯用方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4566498/