Understanding tempfile.TemporaryFile

John Machin sjmachin at lexicon.net
Thu Dec 27 22:12:43 EST 2007


On Dec 28, 1:49 pm, byte8b... at gmail.com wrote:
> Wondering if someone would help me to better understand tempfile. I
> attempt to create a tempfile, write to it, read it, but it is not
> behaving as I expect. Any tips?
>
> >>> x = tempfile.TemporaryFile()
> >>> print x
>
> <open file '<fdopen>', mode 'w+b' at 0xab364968>
>
> >>> print x.read()
> >>> print len(x.read())
> 0
> >>> x.write("1234")
> >>> print len(x.read())
> 0
> >>> x.flush()
> >>> print len(x.read())
>
> 0

This is nothing particular to your subject; it applies to all files.

x.read() starts reading at the CURRENT POSITION, not at the start of
the file. In all cases above, the then current position was the END of
the file, so x.read() returned a zero-length string.

Check out the seek method.



More information about the Python-list mailing list