Showing posts with label open. Show all posts
Showing posts with label open. Show all posts

Saturday, November 10, 2012

Python open and read integers from binary file

How embarassing that I had to look this up. Here is the syntax in python for opening a binary file:

f = open("filename", "rb")
.
.
f.close()

From this example:

http://stackoverflow.com/questions/4971413/how-to-read-a-binary-file

This was part of a larger search where I was working on pulling values out of a (packet, obviously) binary file. The horrific answer was to read bytes from the file into a "string", then bust out each 8-bit (or other size) value as an integer. So what I ended up doing was reading in 6 "characters", yanking out the packet size from this primary header, and then using that value to read in another "string" of that many characters + 1.

Here is one example site, in which the read() command is used and the result is cast to different sizes of integers:

http://stackoverflow.com/questions/1163459/reading-integers-from-binary-file-in-python

Here is another example where bytes are read in one or chunksize at a time with a loop:

http://stackoverflow.com/questions/1035340/reading-binary-file-in-python