Last Updated: September 29, 2021
·
58.1K
· mzungu777

Reading/writing binary data in Python

So, you want to read individual bytes of a file in Python? How about writing individual bytes back in? As with most things in Python, it's both very easy and also kind of weird.

Some googling led me to this answer on Stack Overflow. Easy, right? Open a file, read one position at a time. No problem.

Only thing is, if you print out whatever it was you just read into your variable (oh, Python), you have a character. Specifically, the character whose ASCII value is the value of the byte.

So, if you actually want to do something with that value, you probably want to convert it into an integer (between 0 and 255). Super easy! Just use the ord() function an there you are.

How about writing individual bytes into a binary file? Also really easy. From poking around, I found this forum discussion which implied you could put everything into a string and write that out to a file. That's right - take an empty string, and for each integer value you want to right into a byte (between 0 and 255), run it through chr() (the inverse of ord()) to change it back into a character, and append that to the string. When you're done, simply write that string to a file, and you're done!

(For demo code sample, see my blog post.)