ด้วยไฟล์ข้อความ ฉันสามารถเขียนสิ่งนี้ได้:
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 หรือไม่?