How to open an HTML file in the Browser using Python

avatar
Borislav Hadzhiev

Last updated: Apr 11, 2024
6 min

banner

# Table of Contents

  1. How to open an HTML file in the Browser using Python
  2. Open an HTML file from a remote URL in the browser using Python
  3. Open an HTML file in the Browser in Python using webbrowser.open()
  4. Open an HTML file in the browser using subprocess.call()
  5. How to open an HTML file for reading/writing in Python
  6. Open an HTML file in reading mode using codecs.open()

Note: if you need to open an HTML file for reading/writing in Python, click on the following subheading:

# How to open an HTML file in the Browser using Python

To open an HTML file in the browser using Python:

  1. Import the webbrowser built-in module.
  2. Use the webbrowser.open_new_tab() method to open the HTML file in the browser.
main.py
import webbrowser file_path = 'index.html' html_string = """ <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <h2>bobbyhadz.com</h2> <h2 style="background-color: lime;">google.com</h2> </body> </html> """ with open(file_path, 'w', encoding='utf-8') as html_file: html_file.write(html_string) webbrowser.open_new_tab(file_path)
The code for this article is available on GitHub

Running the code sample with python main.py produces the following output.

open html file in browser using python

We used the with open() statement to open the index.html file in w (write) mode and wrote an HTML template in the file.

main.py
with open(file_path, 'w', encoding='utf-8') as html_file: html_file.write(html_string)

The following index.html file is produced.

write html in file

The last step is to use the webbrowser.open_new_tab() method to open the file in the browser.

The method takes a file path or a URL as a parameter and opens it in a new tab of the default browser (e.g. Chrome).

main.py
file_path = 'index.html' webbrowser.open_new_tab(file_path)

We specified a relative file path in the example, however, in some cases, you might have to specify an absolute path.

main.py
import webbrowser import os file_path = 'index.html' html_string = """ <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <h2>bobbyhadz.com</h2> <h2 style="background-color: lime;">google.com</h2> </body> </html> """ with open(file_path, 'w', encoding='utf-8') as html_file: html_file.write(html_string) webbrowser.open_new_tab(f'file://{os.getcwd()}/{file_path}')
The code for this article is available on GitHub

The code sample uses the file:// prefix and the os.getcwd() method to get a string that represents the current working directory.

main.py
import os file_path = 'index.html' # ๐Ÿ‘‡๏ธ file:///home/borislav/Desktop/bobbyhadz_python/index.html print(f'file://{os.getcwd()}/{file_path}')

We used a formatted string literal to concatenate the strings.

You can achieve the same result by using the os.path.realpath() method.

main.py
import webbrowser import os file_path = 'index.html' html_string = """ <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <h2>bobbyhadz.com</h2> <h2 style="background-color: lime;">google.com</h2> </body> </html> """ with open(file_path, 'w', encoding='utf-8') as html_file: html_file.write(html_string) webbrowser.open_new_tab(f'file://{os.path.realpath(file_path)}')
The code for this article is available on GitHub

The os.path.realpath() method returns the canonical path of the supplied filename.

main.py
import os file_path = 'index.html' # ๐Ÿ‘‡๏ธ file:///home/borislav/Desktop/bobbyhadz_python/index.html print(f'file://{os.path.realpath(file_path)}')

If you need to open the URL in a new browser window instead of a new tab, use the webbrowser.open_new() method.

main.py
import webbrowser import os file_path = 'index.html' html_string = """ <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <h2>bobbyhadz.com</h2> <h2 style="background-color: lime;">google.com</h2> </body> </html> """ with open(file_path, 'w', encoding='utf-8') as html_file: html_file.write(html_string) webbrowser.open_new(f'file://{os.path.realpath(file_path)}')
The code for this article is available on GitHub

Note: if you need to open an HTML file for reading/writing in Python, click on the following subheading:

# Open an HTML file from a remote URL in the browser using Python

You can also use the open_new_tab() method to open an HTML file from a remote URL in the browser.

main.py
import webbrowser url = "https://docs.python.org/3/library/webbrowser.html" webbrowser.open_new_tab(url)

The webbrowser.open_new_tab() method will open the supplied URL in a new tab if a browser window is already open.

If you need to open the URL in a new browser window, use the webbrowser.open_new method instead.

main.py
import webbrowser url = "https://docs.python.org/3/library/webbrowser.html" webbrowser.open_new(url)

# Open an HTML file in the Browser in Python using webbrowser.open()

You can also use the webbrowser.open method to open an HTML file in the browser using Python.

main.py
import webbrowser import os file_path = 'index.html' html_string = """ <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <h2>bobbyhadz.com</h2> <h2 style="background-color: lime;">google.com</h2> </body> </html> """ with open(file_path, 'w', encoding='utf-8') as html_file: html_file.write(html_string) same_browser_window = 0 new_browser_window = 1 new_browser_tab = 2 webbrowser.open(url=f'file://{os.path.realpath(file_path)}', new=2)
The code for this article is available on GitHub

Running the code sample with python main.py produces the following output.

open html file in browser using python

The webbrowser.open() method displays the supplied URL using the default browser.

The new argument can be set to 3 possible values:

  • 0 - opens the URL in the same browser window.
  • 1 - opens the URL in a new browser window.
  • 2 - opens the URL in a new browser tab.

Note: if you need to open an HTML file for reading/writing in Python, click on the following subheading:

# Open an HTML file in the browser using subprocess.call()

You can also use the os.startfile (Windows) and subprocess.call (macOS and Linux) methods to open an HTML file in the browser.

main.py
import os import subprocess file_path = 'index.html' html_string = """ <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <h2>bobbyhadz.com</h2> <h2 style="background-color: lime;">google.com</h2> </body> </html> """ with open(file_path, 'w', encoding='utf-8') as html_file: html_file.write(html_string) absolute_file_path = f'{os.path.realpath(file_path)}' try: # opens file in browser on Windows os.startfile(absolute_file_path) except AttributeError: try: # opens file in browser on macOS and Linux subprocess.call(['open', absolute_file_path]) except Exception as e: print('An exception occurred: ', e)
The code for this article is available on GitHub

Running the code sample with python main.py produces the following output.

open html file in browser using python

The os.startfile() method starts a file with its associated application.

The associated application of HTML files is your default browser.

However, the os.startfile() method is only available on Windows.

We used the subprocess.call() method to open the file in the browser on macOS and Linux.

The method runs the supplied command.

# How to open an HTML file for reading/writing in Python

If you need to open an HTML file for reading/writing in Python, use the with open() statement and specify the mode.

For example, you can use the w mode for writing and the r mode for reading.

main.py
file_path = 'index.html' html_string = """ <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <h2>bobbyhadz.com</h2> <h2 style="background-color: lime;">google.com</h2> </body> </html> """ # โœ… Open file for writing with open(file_path, 'w', encoding='utf-8') as html_file: html_file.write(html_string) # โœ… Open file for reading with open(file_path, 'r', encoding='utf-8') as html_file: print(html_file.readlines())
The code for this article is available on GitHub

Running the code sample produces the following output.

main.py
['\n', '<!DOCTYPE html>\n', '<html lang="en">\n', ' <head>\n', ' <meta charset="UTF-8" />\n', ' </head>\n', ' <body>\n', ' <h2>bobbyhadz.com</h2>\n', '\n', ' <h2 style="background-color: lime;">google.com</h2>\n', ' </body>\n', '</html>\n']

open html file for reading or writing in python

We used the with open() statement to open the file for writing (w) and reading (r).

The with statement takes care of automatically closing the file even if an error occurs.

The first call to the open() method opens the file in writing mode.

main.py
# โœ… Open HTML file for writing with open(file_path, 'w', encoding='utf-8') as html_file: html_file.write(html_string)

We used the file.write() method to write the HTML template to the file.

The second call to the open() method opens the file in reading mode.

main.py
# โœ… Open HTML file for reading with open(file_path, 'r', encoding='utf-8') as html_file: print(html_file.readlines())

The file.readlines() method returns an array containing the lines in the file.

If you need to read the contents of the HTML file into a string, use the file.read() method instead.

main.py
file_path = 'index.html' html_string = """ <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <h2>bobbyhadz.com</h2> <h2 style="background-color: lime;">google.com</h2> </body> </html> """ with open(file_path, 'w', encoding='utf-8') as html_file: html_file.write(html_string) with open(file_path, 'r', encoding='utf-8') as html_file: print(html_file.read())

read contents of html file into a string

The code for this article is available on GitHub

# Open an HTML file in reading mode using codecs.open()

If your HTML file contains special characters that weren't legible using the previous approach, try using the codecs.open method.

main.py
import codecs file_path = 'index.html' html_string = """ <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <h2>bobbyhadz.com</h2> <h2 style="background-color: lime;">google.com</h2> </body> </html> """ with open(file_path, 'w', encoding='utf-8') as html_file: html_file.write(html_string) with codecs.open(file_path, 'r', encoding='utf-8') as html_file: # ๐Ÿ‘‡๏ธ store the file's output into a list # print(html_file.readlines()) # ๐Ÿ‘‡๏ธ store the file's output into a string print(html_file.read())
The code for this article is available on GitHub

The codecs.open() method opens an encoded file using the given mode.

By default, the mode argument is set to r (reading mode).

The encoding argument is used to specify the encoding that is used for the file.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev