I just recently learned about the iter function's second argument which can be used to loop until a certain condition is met.
with open(file, 'r') as f:
for chunk in iter(lambda _ : f.read(8192), ''):
print(chunk)
However, since iter accepts only functions, I could only code a similar thing for a list by converting it into a generator function and it to iter. Hence, I was wondering if there was a more pythonic way of doing this. Kindly note I have already seen Padraic's answer and I am specifically referring to just an equality condition.
another approach is with a generator
def file_iterator(filehandle, chunksize=8192, sentinel=''):
while True:
result = f.read(chunksize)
if result == sentinel:
return
yield result
with open(file, 'r') as f:
for chunk in file_iterator(file):
print(chunk)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.