Problem with .next() method adding junk characters.

Paul McGuire ptmcg at austin.rr._bogus_.com
Mon Oct 2 09:31:09 EDT 2006


"Fredrik Lundh" <fredrik at pythonware.com> wrote in message 
news:mailman.1076.1159776001.10491.python-list at python.org...
> "Rainy" <ak at silmarill.org> wrote:
>
>> I'm just curious as to what's happening. I understand that you're not
>> supposed to call .next on a file open for writing. But I don't know why
>> and how it does what happened here; besides, I've seen the same thing
>> happen before when I was doing something else with file
>> open/write/close, but I don't remember the specifics.
>
> C's stdio library require you to call "flush" when switching between 
> reading and
> writing; if you don't, the result is undefined.
>
> </F>
>

Sure enough, following the OP's original sequence, with an intervening flush 
between the writes and next, leaves the file in the expected state:

>>> f = file("xyzzy.dat","w")
>>> f.write("1\n")
>>> f.write("2\n")
>>> f.write("3\n")
>>> f.flush()
>>> f.next()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
IOError: [Errno 9] Bad file descriptor
>>> f.close()
>>> f = file("xyzzy.dat")
>>> f.next()
'1\n'
>>> f.next()
'2\n'
>>> f.next()
'3\n'
>>> f.next()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
StopIteration
>>>

I would guess then that the likely extent of any fix to this "bug" would be 
documentation to the effect of Fredrik's last comment above.

-- Paul





More information about the Python-list mailing list