С текстовым файлом я могу написать это:
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?