[Python-Dev] Rationale for NamedTemporaryFile revisited [SEC=UNCLASSIFIED]

Graham Horler graham.horler at gmail.com
Sat Jan 19 08:57:34 CET 2008


On 18 Jan 2008, 06:42:26, Steve Holden wrote:
> Ole.Nielsen at ga.gov.au wrote:
> > Thank you very much for the quick reply.
> > 
> > I believe we have to close the file in order be able to read it in - in this
> > case to feed a unittest. I actually tried to read it in before closing it,
> > but (as I suspected) the data wasn't available.
> The mistake you made was to change the mode from the default "w+b". The 
> following code works on both Windows and Linux:
> 
> from tempfile import NamedTemporaryFile
> fid = NamedTemporaryFile(mode='w+b',
>                           suffix='.tmp',
>                           dir='.')
> 
> fid.write('My temp file')
> fid.seek(0)
> data = fid.read()
> print data
> fid.close()

If you need to read the data by opening the file again (from unittest
code for example), then you need to call fid.flush() (no need for seeking).

Again, comp.lang.python, but I could not resist.

regards.


More information about the Python-Dev mailing list