|
|
|||||||||
|
|||||||||
| |||||||||
|
|
|
| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
|
|
Get inside! Sample the range of functionality easily built with JMSL Library for Time Series Data Analysis, Heat Maps, Portfolio Optimization, Monte Carlo Simulation, Stock Price Charting and more. Download Now! |
|
#1
|
|||
|
|||
|
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
|
||||
|
||||
|
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. |
|
#3
|
|||
|
|||
|
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. |
![]() |
| Viewing: Dev Shed Forums > Programming Languages > Python Programming > Reading Binary |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|