[Tutor] reading binary files

bob gailer bgailer at gmail.com
Tue Feb 3 20:52:55 CET 2009


etrade.griffiths at dsl.pipex.com wrote:
> Data format:
>
> TIME      1  F  0.0
> DISTANCE 10  F  0.0 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0
>
> F=float, D=double, L=logical, S=string etc
>
>   
> The first part of the file should contain a string (eg "TIME"),
> an integer (1) and another string (eg "F") so I tried using
>
> import struct
> in_file = open(file_name+".dat","rb")
> data = in_file.read()
> items = struct.unpack('sds', data)
>
> Now I get the error
>
> error: unpack requires a string argument of length 17
>
> which has left me completely baffled! 
>
>   

Did you open the file with mode 'b'? If not change that.

You are passing the entire file to unpack when you should be giving it 
only the first "line". That's why is is complaining about the length. We 
need to figure out the lengths of the lines.

Consider the first "line"

TIME      1  F  0.0

There were (I assume)  4 FORTRAN variables written here: character 
integer character float. Without knowing the lengths of the character 
variables we are at a loss as to what the struct format should be. Do 
you know their lengths? Is the last float or double?

Try this: print data[:40] You should see something like:

TIME...\x01\x00\x00\x00...F...\x00\x00\x00\x00...DISTANCE...\n\x00\x00\x00

where ... means 0 or more intervening stuff. It might be that the \x01 
and the \n are in other places, as we also have to deal with "byte 
order" issues.

Please do this and report back your results. And also the FORTRAN 
variable types if you have access to them.


-- 
Bob Gailer
Chapel Hill NC
919-636-4239


More information about the Tutor mailing list