Creating and Viewing HTML files with Python (original) (raw)

Last Updated : 24 Jan, 2021

Python is one of the most versatile programming languages. It emphasizes code readability with extensive use of white space. It comes with the support of a vast collection of libraries which serve for various purposes, making our programming experience smoother and enjoyable.

Python programs are used for:

With this said, let us see how we can use python programs to generate HTML files as output. This is very effective for those programs which are automatically creating hyperlinks and graphic entities.

Creating an HTML file in python

We will be storing HTML tags in a multi-line Python string and saving the contents to a new file. This file will be saved with a .html extension rather than a .txt extension.

Note: We would be omitting the standard declaration!

Python3

f = open ( 'GFG.html' , 'w' )

html_template =

f.write(html_template)

f.close()

The above program will create an HTML file:

Viewing the HTML source file

In order to display the HTML file as a python output, we will be using the codecs library. This library is used to open files which have a certain encoding. It takes a parameter encoding which makes it different from the built-in open() function. The open() function does not contain any parameter to specify the file encoding, which most of the time makes it difficult for viewing files which are not ASCII but UTF-8.

Python3

import codecs

f = open ( 'GFG.html' , 'w' )

html_template =

f.write(html_template)

f.close()

file = codecs. open ( "GFG.html" , 'r' , "utf-8" )

print ( file .read())

Output:

Viewing the HTML web file

In Python, webbrowser module provides a high-level interface which allows displaying Web-based documents to users. The webbrowser module can be used to launch a browser in a platform-independent manner as shown below:

Python3

import webbrowser

webbrowser. open ( 'GFG.html' )

Output:

True