Reputation: 2193
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?
Upvotes: 39
Views: 41347
Reputation: 369074
Convert the filename to url using urllib.pathname2url
:
import os
try:
from urllib import pathname2url # Python 2.x
except ImportError: # Don't use just "except:"
from urllib.request import pathname2url # Python 3.x
url = 'file:{}'.format(pathname2url(os.path.abspath('1.html')))
webbrowser.open(url)
Upvotes: 7
Reputation: 25332
With latest versions of Python I believe that a better API to open a local file would be:
import webbrowser
import pathlib
webbrowser.open(pathlib.Path(target_as_str).as_uri())
Upvotes: 0
Reputation: 12939
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))
Upvotes: 57