2014-02-25 20 views
20

我有一個Python文件html_gen.py它寫一個新的html文件index.html在同一目錄下,並想開闢index.html當書寫完成。webbrowser.open()在python

所以我寫了

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

但執行.py文件後沒有發生。如果我把代碼

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

Safari執行代碼時將打開谷歌的FrontPage。

我不知道如何打開本地的index.html文件?

+1

看到這個答案:http://stackoverflow.com/a/5943706/771848 – alecxe

+0

DO如果你調用內建'open('index.html')',你會得到一個錯誤?它會檢查您是否可以打開文件進行閱讀。 – jfs

+0

無法在Python 2.7.6,Ubuntu 14.04,Firefox 47上重現。 –

回答

30

嘗試在URL的開頭指定「file://」。此外,使用文件的絕對路徑:

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

注意:需要導入Python os模塊才能正常工作:import os –

+0

不適用於我。 – IARI

4

轉換的文件名使用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)