34
votes

I have a python file html_gen.py which write a new html file index.html in the same directory, and would like to open up the index.html when the writing is finished.

So I wrote

import webbrowser
webbrowser.open("index.html");

But nothing happen after executing the .py file. If I instead put a code

webbrowser.open("http://www.google.com")

Safari will open google frontpage when executing the code.

I wonder how to open the local index.html file?

2
do you get an error if you call builtin open('index.html') ? It checks whether you can open the file for reading. - jfs
Cannot reproduce on Python 2.7.6, Ubuntu 14.04, Firefox 47. - Ciro Santilli 新疆再教育营六四事件法轮功郝海东
webbrowser.open('index.html', new=2, autoraise=True) works fine, is the semi-colon breaking it? - user3121518

2 Answers

53
votes

Try specifying the "file://" at the start of the URL. Also, use the absolute path of the file:

import webbrowser, os
webbrowser.open('file://' + os.path.realpath(filename))
7
votes

Convert the filename to url using urllib.pathname2url:

import os
try:
    from urllib import pathname2url         # Python 2.x
except:
    from urllib.request import pathname2url # Python 3.x

url = 'file:{}'.format(pathname2url(os.path.abspath('1.html')))
webbrowser.open(url)