In Python, how do I read in a binary file and loop over each byte of that file?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Python >= 3.8
Thanks to the walrus operator (
:=) the solution is quite short. We readbytesobjects from the file and assign them to the variablebytePython >= 3
In older Python 3 versions, we get have to use a slightly more verbose way:
Or as benhoyt says, skip the not equal and take advantage of the fact that
b""evaluates to false. This makes the code compatible between 2.6 and 3.x without any changes. It would also save you from changing the condition if you go from byte mode to text or the reverse.Python >= 2.5
In Python 2, it’s a bit different. Here we don’t get bytes objects, but raw characters:
Note that the with statement is not available in versions of Python below 2.5. To use it in v 2.5 you’ll need to import it:
In 2.6 this is not needed.
Python 2.4 and Earlier