Friday, July 8, 2016

Using Python to create and view HTML file


This post uses Python to create and view an HTML file. HTML file is a file type that has an extension of .html and you can use any browser to look at its contents.

Here you will learn how to create HTML files with Python scripts, and how to use Python to automatically open an HTML file in any browser of your choice such as Chrome, Firefox, Opera, Safari, Edge, etc.

If you don't know anything about HTML, I recommend that you take some few minutes to study the W3 Schools HTML tutorial before continuing. We’re going to be creating an HTML document using Python, so you will have to know what an HTML document is!

What we’re going to do now is create an HTML file that says “Hello World” in HTML using Python. This is made possible by storing HTML tags in a multi-line Python string and saving the contents to a new file with a .html extension.

Save the below code as "" and execute it.

# Import the webbrowser module, so we cause it to open the created html file in a deafualt browser
import webbrowser

# We create & open the html file using the open() method in write mode and store it in an object (f)
f = open('myhtml.html','w')

# Store our html code in a variable named "message" using mutli-line string 
message = """
     HTML file with Python 


Hello World!

Tutorial by
""" # Call the writ() method to write the content of the "message" variable into the html file object (f) f.write(message) # we close the file after writting into it f.close() # we now use the webbrowser module to open the created html file in a deafualt web browser webbrowser.open_new_tab('myhtml.html')

The comments within the code explains all the steps we took to create an HTML file that says “Hello World” in HTML using Python and opens it a default web browser on our windows PC.

That is it!
Happy reading.

No comments:

Post a Comment