Forum Archive

Open files in the webbroser via the file:/// url scheme

halloleo235

With Pyhonista I want to write a small documentation viewer for html files I have created in Pythonista.

Let's say I have created a file "doco.html" under Pythonista's local file area. How can I view such a file via the webbrowser module?

webbrowser.open("file:///doco.html")

does not work for me. However the file certainly exists: With open("doco.html") as f I can read the lines of the html file straight away.

omz

You need to use the full path for a file URL, i.e. it needs to include the current directory path. You can get that via os.getcwd(). Here's a full example:

import os
import urllib
import webbrowser

filename = 'doco.html'
with open(filename, 'w') as f:
    f.write('

Hello World

') full_path = os.path.join(os.getcwd(), filename) fileurl = 'file://' + urllib.pathname2url(full_path) webbrowser.open(fileurl)
halloleo235

Many thanks, omz. That's exactly what I want! :-)