[Tutor] need help with syntax

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Wed Jan 11 11:46:13 CET 2006


On Tue, 10 Jan 2006, bill nieuwendorp wrote:

> I am trying to convert binary file to ascii
>
> here is the format spec
>
> steps = int 4
> value = int 4
> time = float 4 * steps


Hi Bill,

Ok, that structure seems fairly simple so far.


> >>> import struct
> >>> import string
> >>> f = file('binary_file','rb')
> >>> line = f.readline()
             ^^^^^^^^^^^^

Ah.  Don't do this.  *grin*

If our file is binary, the only safe function we can use to read from such
a file is read().  "newlines()" just shouldn't be a concept in binary
files: using readline() on a binary file is a major no-no.

Imagine what happens if your file only contains ten steps.  As a hint:
look at ord('\n').


You mentioned earlier that you're expecting an integer, an integer, and
then a sequence of float.  Don't count bytes if you can help it: let
Python's struct.calcsize() do this for you.

    http://www.python.org/doc/lib/module-struct.html

Your machine may align bytes differently than you might expect: it may be
best to let the machine handle that for you.


Best of wishes to you!



More information about the Tutor mailing list