Adam Luptak

Read/write binary data in Python

Python
Aug. 30, 2012

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 a demonstration, see the attached code; it's a simple method that will take a file, read each individual byte, convert it to an integer, convert it back, and write them out to a new file.