Thread: Reading Binary

    #1
  1. No Profile Picture
    Junior Member
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2003
    Posts
    6
    Rep Power
    0

    Reading Binary


    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!
  2. #2
  3. Hello World :)
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Mar 2003
    Location
    Hull, UK
    Posts
    2,537
    Rep Power
    69

    Binary a'


    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..

    Code:
    file = open('filename', 'rb').read()
    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).

    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.

    Have fun,
    Mark.
  4. #3
  5. No Profile Picture
    Junior Member
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2003
    Posts
    6
    Rep Power
    0
    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[0] #etc. etc.
    Last edited by shochu; July 1st, 2003 at 10:08 AM.

IMN logo majestic logo threadwatch logo seochat tools logo