reading in ints from binary files

Siegfried Gonzi siegfried.gonzi at kfunigraz.ac.at
Sun Mar 24 17:56:39 EST 2002


"Bill" <metaliu at yahoo.com> schrieb im Newsbeitrag
news:a7ns1d$mi1$1 at nntp1.jpl.nasa.gov...
> Quick Newb question:
>
> How do I read in integers from binary files?  readlines() reads returns
the
> data in as a string.  I can manipulate the string to get the desired
result.
> However, is there an easier way of doing this?  I currently do something
> like:
>
> f=open('file', 'rb')
> s = f.readline()
> l = list(s[0:-1])
> l.reverse()
> a = array.array('h', ''.join(l))

I had a similar problem: reading a binary array of dimension 360x180. The
satellite-datas have been stored in floating-point format. I am relatively
new to Python, but the following function just works (and it is quite fast,
at least I am contented with):

def readBinArray(file,rows,cols,trans='nein',what='f'):
     f = open(file,'rb')
     #
     ergArray = array(what)
     n = cols*rows
     ergArray.fromfile(f,n)
     f.close()
     ergArray.byteswap()
     ergArray = reshape(ergArray,(rows,cols))
     if trans == 'ja':
          return transpose(ergArray)
     return ergArray

It is based on the Numeric-library (but this is not a condition; I just only
passed the array on to a DISLIN-plotting library, hence also the
transposing). Important here is "fromfile(f,n)" and "array(what)". You
should look after what you have to use in array() in order to create an
array dedicated to integers (e.g. 'f' means floating-point in Python
notation).

If your file is a Unix-file and you read it on Windows, maybe you should
also apply byteswap().

So, the above shows Python's strength . It seems the Python developers had
the better common-sense when it comes to "Python and the real world" (as
opposed to Clean and in the binary-specific case even Common Lisp*).

S. Gonzi
*Surely, Common Lisp programmers believe that they are God, and God dictates
what you may and what not. All the Gods decided we just only use ASCI-files.
There is only one caveat: my NASA-binary-satellite-data-files do not care on
ASCI-files. Please, no suggestions like: "But you can do it  in Lisp with a
little bit investment on work". Okay, agreed, but then the Lisp fanatics
should stop accusing Python or Perl,...infinitely (until Cantor says: Lisp
fanatic stop, you are reaching God's realm).







More information about the Python-list mailing list