If you want to read in a binary file and loop over each byte of that file In Python 3, it is a bit different. Here we will no longer get raw characters from the stream in byte mode rather than this we get the byte objects, so we need to change the condition:
with open("myfile", "rb") as f:
byte = f.read(1)
while byte != b"":
# Do stuff with
byte. byte = f.read(1)
You have another method where the generator yields bytes from a file for reading the file in chunks:
def bytes_from_file(filename, chunksize=8192):
with open(filename, "rb") as f:
while True:
chunk = f.read(chunksize)
if chunk:
for b in chunk:
yield b
else:
break
# example:
for b in bytes_from_file('filename'):
do_stuff_with(b)