file object, details of modes and some issues.
jepler at unpythonic.net
Tue Aug 26 21:24:33 CEST 2003
On Tue, Aug 26, 2003 at 06:37:03PM +0000, Michael Hudson wrote:
> simon place <simon_place at lineone.net> writes:
> > is the code below meant to produce rubbish?
> Python uses C's stdio. According to the C standard:
> >, i had expected an exception.
> > f=file('readme.txt','w')
> > f.write(' ')
> > f.read()
> engages in undefined behaviour (i.e. is perfectly entitled to make
> demons fly out of your nose). You can apparently trigger hair-raising
> crashes on Win98 by playing along these lines. There's not a lot that
> Python can do about this except include it's own implementation of a
> stdio-a-like, and indeed some future version of Python may do just
If it's true that stdio doesn't guarantee an error return from fwrite() on
a file opened for reading, then the Python documentation should be
changed (it claims an exception is raised, but this depends on the
return value being different from the number of items written
It's my feeling that this is intended to be an error condition, not
undefined behavior. But I can't prove it. Here are some relevant pages
from the SUS spec, which intends to follow ISO C:
Hm, and there's a bug even on Linux:
>>> f = open("/dev/null", "r")
>>> f.write("") # should cause exception (?)
>>> # nope, it doesn't
>>> f.write(" ") # should also cause exception
Traceback (most recent call last):
File "<stdin>", line 1, in ?
IOError: [Errno 9] Bad file descriptor
>>> # yep!
More information about the Python-list