June 25th, 2003, 11:11 AM
Hi I'm totally new to python and have had no experience reading binary files so I might be totally off here.
I have a file which consists of 16 bit unsigned short ints, one right after the other. The file is in binary. I want to read it in and print the ints but not as binary as actual ints.
I tried just reading the file in two bytes at a time using read() and then printing the data but that just printed unreadable stuff.
Something like this...
file = open(filename, 'rb')
data = int(file.read(2))
print data #doesn't work of course
Anyone know how I could do this or if I can do it at all?? Thanks for the help!
June 25th, 2003, 02:59 PM
Well I'm impressed, for a total newbie to Python you worked out how to read in a binary file correctly the first time. here's a quick example anyway..
I think the problem your having is that binary files are generally compiled or "not in plain english" and contain a whole bunch of strange and wonderful charactars. (please correct me if i'm wrong).
file = open('filename', 'rb').read()
Could you possibly attach the file your trying to read so I can see what your working with, you might also want to try opening the file in your favourate text editor and seeing if the content is readable or not.
To read binary you can use the struct module or the array module.
If you want to use the array module it needs to be one consistent type (ie. all chars, all ints, all floats)
You can stream the entire binary file into the array.
For instance, in my case I used 16 bit integers so the code is as follows
from array import *
data = array('h') #h is the type, fill in whatever type you need
data.fromfile(file, numBytes) #numBytes is how many bytes you want to read in
data.byteswap() #nifty little function for going from little to big endian or vice versa
That's it! You can then access each piece of data jsut like normal
print data #etc. etc.
Last edited by shochu; July 1st, 2003 at 10:08 AM.