Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (47.6k points)

In Python, how do I read in a binary file and loop over each byte of that file?

1 Answer

0 votes
by (106k points)

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)

Related questions

0 votes
1 answer
asked Oct 15, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...