Converting binaty to ascii

Xavier Combelle xcombelle at kedros.com
Thu Feb 19 10:22:43 EST 2004


>Actually I think is more-or-less standard. The only detailed info I have
> is a so called "tracciato record" (may be "record track" in English)
>in which there is a precise description of "what is where" and how
>long (I do not know precisely the unit of measure...sorry for my
>ignorance) the field is but no info about format.
>  
>
That would be easier with the record track.
The fact is that  a binary file is never standard, in it depend a
lot of the kind of language/hardware which generate it.
The unit of measure is probably the byte

The easier case is if all your data is in ascii format.
for example, if you have a file which is named data.dat
which contain 2 records of 20 bytes each with three fields (5bytes, 10 
bytes, 5 bytes)

data1DATA2_____data3'ata1'ATA2_____'ata3

you can extract it  by using this code

import struct

#here the format of the record
fmt = "5s10s5s"

#caluclate the total size of the record                          
size = struct.calcsize(fmt)

f = file("data.dat")
#read one record
s = f.read(size)
while s:
    print "read =", s
#extracct fields of the record
    d1,d2,d3 = struct.unpack(fmt,s)
#use the record for whatever you want
    print "unpack",d1,d2,d3
#read next record
    s = f.read(size)

here the result of the script

read = data1DATA2_____data3
unpack data1 DATA2_____ data3
read = 'ata1'ATA2_____'ata3
unpack 'ata1 'ATA2_____ 'ata3


The hard point is probably to find the formart string,
but by using the infos you have and the struct help page
http://python.org/doc/2.3.3/lib/module-struct.html
you should succeed.




More information about the Python-list mailing list