[Tutor] How to write list to file

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Wed Jan 28 13:33:00 EST 2004



On Wed, 28 Jan 2004, Vicki Stanfield wrote:

> > I have the following code:
> >
> > print bytearray[0:bytetotal]
> > outfile.write("[")
> > for byte in bytearray[0:bytetotal]:
> >     outfile.write(byte)
> > outfile.write("]")
> >
> > The print statement prints this:
> >
> > ['F', '8', '\t']
> >
> > but the outfile has only this:
> >
> > [40	]
> >
> > I think the problem is that the program is trying to write [40 46 30 38
> \t], but for some reason stops at the 40. Why would the different way of
> writing cause this behavior?
> >
> Actually what I was thinking doesn't make sense. I know that the F is a
> 46 and the 8 is a 38 in hex. I am not sure where the 40 comes from.



Hi Vicki,

I'm not quite sure I understand quite yet this problem.  *grin*



But I'm guessing that '40\t' is meant to be interpreted as the characters
'4', '0', and '\t', but not as the number '40' followed by a tab.


Assuming that 'bytetotal' is 3, the three characters that you're writing:

    ['F', '8', '\t']

should correspond to the three bytes that you see in your file (plus the
two from the brackets).



Before we try figure out any more: is that code snippet the only part of
your program, or do you do some additional writing to file either before
or after this snippet?  What I don't get quite yet is how you're getting
'40\t' from the outfile:


> > but the outfile has only this:
> >
> > [40	]


There's something slightly irrational here, and I can't help but feel
we're not seeing something obvious.  *grin*


Given that the array contained ['F', '8', '\t'], after the loop, you
should be seeing

###
[F8	]
###

in your file.  Are you doing any file seek()ing after this snippet?  And
have you made sure to explicitely close() the outfile?


Good luck to you!




More information about the Tutor mailing list