Re: Reading a binary file with Jython

  • To: Cicero Augusto Wollmane Zandona <cicero@xxxxxxxxxx>
  • Subject: Re: Reading a binary file with Jython
  • From: Tom Whittaker <tomw@xxxxxxxxxxxxx>
  • Date: Wed, 29 Aug 2001 09:03:09 -0500
Hi Cicero:

> I am not sure if this mailing list is also about Jython (if is not please
> tell me). Athogh Jython is very helpfull, the documentation is a litle
> poor yet.

One thing I've found - since Jython is intended to be Python, then you can
usually rely on the Python documentation for any non-Java stuff.  

There is a Jython users mailing list at:
http://jython.sourceforge.net/
Just click on "Mailing Lists (exit)" under Resources on the left side of this
page, and you can subscribe and/or browse the archives.

> 
> Ok here is the problem: I heve a binary file created in C that is an
> array of 4-bytes-float 512x512. And I cant read it. The Jython tutorial
> tells only how to read a text file (the method readlines()). I imagine
> that is a very simple question.

Python treats all files are character streams.  Therefore, when you open a file
and do not want any translation (like newline...), then also use the 'b'
option.
To read a binary file, you will want to use the 'struct' module to translate.
See the doc at:

http://www.python.org/doc/current/lib/module-struct.html

Here's an example:

import struct
f=open("OUTLUSAM", "rb")
g=f.read(12)
h = struct.unpack("3i", g)
print h
(857, 800000, 801490)

The "12" in the read() says read 12 bytes.  The "3i" format in the unpack()
says to translate the 12 bytes in g as 3 integers.  (In your case, you'll want
to use "f" formatting since you have floats.)  The struct formatting has many
options, including byte-order swapping if you need it.  All the info is in the
referenced URL above.

Hope that helps.

tom

-- 
Tom Whittaker (tomw@xxxxxxxxxxxxx)
University of Wisconsin-Madison
Space Science and Engineering Center
Phone/VoiceMail: 608/262-2759
Fax: 608/262-5974


  • 2001 messages navigation, sorted by:
    1. Thread
    2. Subject
    3. Author
    4. Date
    5. ↑ Table Of Contents
  • Search the visad archives: