Reputation: 23783
I'm trying to read a file piece by piece:
def buf_read2(filename, buffer_size):
with open(filename, 'rb') as f:
buffer = f.read(buffer_size)
print buffer # and do other stuff with it
This doesn't read the last chunk of the file. For example, if a file is 129 bytes and I set buffer_size
to 128, the last byte will not be read.
This old school approach works though:
def buf_read1(filename, buffer_size):
f = open(filename, 'rb')
while True:
buffer = f.read(buffer_size)
if not buffer:
break
print buffer # and do other stuff with it
f.close()
What am I doing wrong?
Upvotes: 1
Views: 143
Reputation: 526543
with
isn't a loop, so in your first example, read()
only gets called once.
You still need to include a loop:
with open(filename, 'rb') as f:
while True:
buffer = f.read(buffer_size)
if not buffer:
break
print buffer # and do other stuff with it
Upvotes: 4