problem with struct module

A

Angelo Secchi

I'm trying to use the unpack method in the struct module to parse a
binary file without success. I have a binary file with records that
include many fields for a total length of 1970. Few days ago I was
suggested by the list to use the struct module to parse it using the
following code in the hypothesis that for each records I have just two
fields:

import struct
fmt='10s1960s'
size=struct.calcsize(fmt)
f=file("data")
s=f.read(size)

while s:
print 'read:', s
d1,d2=struct.unpack(fmt,s)
print 'unpack', d1

Probably I was not even able to explain my problem since it seem that
this code is not able to read the file. Can anybody help me, maybe
asking for other infos they need? Also just suggest me a place where I
can find examples of using struc.unpack would be very helpful.
Thanks.
a.




--
========================================================
Angelo Secchi PGP Key ID:EA280337
========================================================
Current Position:
Graduate Fellow Scuola Superiore S.Anna
Piazza Martiri della Liberta' 33, Pisa, 56127 Italy
ph.: +39 050 883365
email: (e-mail address removed) www.sssup.it/~secchi/
========================================================
 
L

Larry Bates

Angelo,

Two things:

1) To open a file for reading binary,
I think you meant to write:

f=open("data","rb")

2) You don't need struct to decode a 10 character
string followed by a 1960 character string (10s1960s).
If they are really strings, just read them normally.
If they are binary data, then you should decode them
using struct, but you wouldn't use 10s1960s as format
you would use binary constructs in the format.

Perhaps more detail on what you "think" the structure
of the 1970 byte "records" is would help us help you.

-Larry
 
N

Noah

Angelo Secchi said:
I'm trying to use the unpack method in the struct module to parse a
binary file without success. I have a binary file with records that

You did not mention what error you got, but I can guess that
it is because you are trying to unpack the structure inside an
infinite loop.

import struct
fmt='10s1960s'
size=struct.calcsize(fmt)
f=file("data")
s=f.read(size)
while s:
print 'read:', s
d1,d2=struct.unpack(fmt,s)
print 'unpack', d1
s = f.read (size) ### YOU FORGOT THIS LINE.

Yours,
Noah
Spurrier
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,773
Messages
2,569,594
Members
45,115
Latest member
JoshuaMoul
Top