webbrowser.open() in python

Question:

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?

Asked By: Lelouch

||

Answers:

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))
Answered By: Al Sweigart

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)
Answered By: falsetru

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())

Answered By: Fabio Zadrozny
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.