[Tutor] tempfile and webbrowser
Kent Johnson
kent37 at tds.net
Sun Sep 3 21:35:58 CEST 2006
yves wrote:
> Hello tutors,
>
> This programm works:
> **********
> import webbrowser
> a = open('test.htm','wb')
> a.write("<html>Test</html>")
> webbrowser.open(a.name)
> a.close()
> ***********
> but I would like to avoid the risk of overwriting an already existing
> "test.htm" file, so I try to use the module tempfile:
> ***********
> import tempfile
> import webbrowser
> a = tempfile.NamedTemporaryFile('w+b',-1,'.html')
> a.write("<html>Test</html>")
> webbrowser.open(a.name)
> #a.close()
> **********
> This does not work (no traceback error though): the browser displays a
> blank page.
The problem is that the file is never actually written because you omit
the close. But when you do close the temp file, it is deleted. Try using
a.flush() instead of a.close(), that will force the file to be written.
Alternately use tempfile.mkstemp() which lets you close the file and
delete it when you are done with it.
Kent
More information about the Tutor
mailing list