[Tutor] tempfile and webbrowser

Alan Gauld alan.gauld at btinternet.com
Mon Sep 4 01:09:09 CEST 2006


> This program works:
> **********
> import webbrowser
> a = open('test.htm','wb')

Any particular feason to open the file in binary mode? 
That can sometimes cause odd things to happen.

> a.write("<html>Test</html>")
> webbrowser.open(a.name)
> a.close()

The close should come before the browser reads 
the file, otherwise you are trying to read a file thats 
still open in write mode and the behaviouir there is 
"undefined" on most operating systems.

> import tempfile
> import webbrowser
> a = tempfile.NamedTemporaryFile('w+b',-1,'.html')

Now you are making it even more complex by using 
a read/write mode binary temporary file!

> a.write("<html>Test</html>")
> webbrowser.open(a.name)
> #a.close()
> **********

> Have you got some suggestions to tackle this problem?

Simplify the file handling to use text files and close the file 
as soon as possible. These are good guidelines for any 
file handling you do.

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld



More information about the Tutor mailing list