[Tutor] Fwd: need help with syntax

Liam Clarke ml.cyresse at gmail.com
Wed Jan 11 04:52:23 CET 2006

oops, forward to list.

---------- Forwarded message ----------
From: Liam Clarke <ml.cyresse at gmail.com>
Date: Jan 11, 2006 4:18 PM
Subject: Re: [Tutor] need help with syntax
To: bill nieuwendorp <slow67 at gmail.com>

On 1/11/06, bill nieuwendorp <slow67 at gmail.com> wrote:
> hello all I am new to python and this list has been helpfull so far
> I am trying to convert binary file to ascii
> here is the format spec
> steps = int 4
> value = int 4
> time = float 4 * steps
> so in the python terminal terminal i convert it like this
> >>> import struct
> >>> import string
> >>> f = file('binary_file','rb')
> >>> line = f.readline()
> >>> L = tuple(line)

Try this -
import struct

f = file('binary_file','rb')
toUnpack = f.read(4)
steps = struct.unpack(">i",toUnpack)[0]
floatBytes = steps * 4
furtherUnpack = f.read(4 + floatBytes) #The first 4 for value
pattern = ">i%df" % steps
data  = struct.unpack(pattern, furtherUnpack)
value = data[0]
time = data[1:]

Or probably simpler to do

f = file('binary_file','rb')
toUnpack = f.read(8)
(steps,value) = struct.unpack(">2i",toUnpack)
floatBytes = steps * 4
furtherUnpack = f.read(floatBytes)
pattern = ">%df" % steps
time = struct.unpack(pattern, furtherUnpack)

You could then call f.readline() to advance to the next line if
needed, although binary data tends not to be line break delimited as

But I found that using f.read(num_of_bytes) is the best way to do
this, especially when the data you're reading is unknown but specified
at a known offset.

You may also want to have a look at f.seek() and f.tell(), and if the
"%d" stuff is unfamiliar you may want to google - 'format string

Good luck, it's a bit tricky at times*, but it works, I built a simple
iPod database parser using f.read() and string substitution for the
struct module patterns.


Liam Clarke

*Like when your brilliant plan to have objects generate patterns for
the data they're working with by checking type founders thanks to

More information about the Tutor mailing list