question on using format in struct module

Chris Barker chrishbarker at home.net
Wed Oct 24 18:35:18 EDT 2001


Suresh wrote:
> I need some help with struct module. I have a binary file (obtained
> with our product) and it contains char, int, float values. I used
> struct module for this purpose in this manner --
 
> import struct
> binfile = open('binary_file.bin','rb')
> format = ????
> bytes = struct.calcsize(format)
> i1, i2 and so on = struct.unpack(format, binfile.read(bytes))
> 
> (i1, i2, i3 etc will have the equivalent text values of the binary
> fields from the "binary_file.bin")

The equivalent TEXT values??? IS that what you want? If so,
struct.unpack won't do it for you directly. It unpacks the bytes into
the appropriate numerical types. If you want strings, you can convert
them to strings afterward by any number of methods (str(), %, ``, etc.)
 
> The problem is specifying for "format" variable. Since my binary file
> has non-uniform and different data types how do I specify for format =
> ????

That's exactly why you have to specigy the format...

> Is there a way I can tell python to decide upon format looking at
> the binary file. 

No. it is just a bunch of bytes to Python, and will mean different
things depending on how it is interpreted. There is no way for Python to
know. Here is an example of how to use it: 

If your file has, for example, two chars, an int and a float in
sequence, the format would be:

format "ccif"

or 

format "2cif"

see the library reference for other format characters, and how to use
them. 

If you still can't figure this out, send us some information about the
file (maybe a snippet of the code that wrote it), or ask the person who
wrote the code that created the file to help you with the format
string(s).

-Chris

-- 
Christopher Barker,
Ph.D.                                                           
ChrisHBarker at home.net                 ---           ---           ---
http://members.home.net/barkerlohmann ---@@       -----@@       -----@@
                                   ------@@@     ------@@@     ------@@@
Oil Spill Modeling                ------   @    ------   @   ------   @
Water Resources Engineering       -------      ---------     --------    
Coastal and Fluvial Hydrodynamics --------------------------------------
------------------------------------------------------------------------



More information about the Python-list mailing list