problem with read() write()

Gertjan Klein gklein at
Sun Nov 1 09:36:33 CET 2009

Alf P. Steinbach wrote:

>So with 'w+' the only way to get garbage is if 'read' reads beyond the end of 
>file, or 'open' doesn't conform to the documentation.

It does read beyond the end of file. This is perhaps the way the
underlying C library works, but it looks like an "unexpected feature"
(read: bug) to me.

I reproduced (with Python 2.5.2 on WinXP) the code the OP wrote after
creating an empty (0-byte) test file; after the write() the read()
returns random garbage. I can't imagine why anyone would want that
behaviour. The file grew to be 4099 bytes after f.close(). I wrote
'hello' to it, so the length of garbage added was 4094 bytes, which I
find a strange number also.

I would have expected the read to return nothing. Can anyone explain or
even defend this behaviour?


More information about the Python-list mailing list