Friday, December 27, 2024
Google search engine
HomeLanguagesHow to write to an HTML file in Python ?

How to write to an HTML file in Python ?

Python language has great uses today in almost every field, it can be used along with other technologies to make our lives easier. One such use of python is getting the data output in an HTML file.

We can save any amount of our input data into an HTML file in python using the following examples in two ways.

Example 1: Creating an HTML file and saving the input data into it.

Approach:

  • Creating an HTML file.
Function_Name = open("Complete_File_Name","File_operation")
  • Adding input data in HTML format into the file.
Function_Name.write("Adding_Input_data_using_HTML_Synatx_separted_by_/n")
  • Saving the HTML file.
Function_Name.close()
  • Opening the HTML file from the saved location.

Below is the implementation:

Python3




# Creating an HTML file
Func = open("GFG-1.html","w")
   
# Adding input data to the HTML file
Func.write("<html>\n<head>\n<title> \nOutput Data in an HTML file \
           </title>\n</head> <body><h1>Welcome to <u>Lazyroar</u></h1>\
           \n<h2>A <u>CS</u> Portal for Everyone</h2> \n</body></html>")
              
# Saving the data into the HTML file
Func.close()


Output:

GFG-1.html file is created in the folder

Checking the Output data of the GFG-1.html file

Example 2: Creating and Saving an HTML file and then adding input data to it.

Approach:

  • Creating an HTML file and saving it.
Function_Name = open("Complete_File_Name","File_operation")
Function_Name.close()
  • Opening the HTML file from the saved location.
  • Now adding input data into the created HTML file.
Function_Name = open(File_Location,"File_operation")
Function_Name.write("Adding_Input_data_using_HTML_Synatx_separted_by_/n")
  • Saving the HTML file.
Function_Name.close()
  • Opening the HTML file from the saved location again to check the output data.

Below is the implementation:

Python3




# Opening the existing HTML file
Func = open("GFG-2.html","w")
  
# Adding input data to the HTML file
Func.write("<html>\n<head>\n<title> \nOutput Data in an HTML file\n \
           </title>\n</head> <body> <h1>Welcome to \
           <font color = #00b300>Lazyroar</font></h1>\n \
           <h2>A CS Portal for Everyone</h2>\n</body></html>")
  
# Saving the data into the HTML file
Func.close()


Output:

Input data is saved into the GFG-2.html file

Checking the Output data of the GFG-2.html file

We’ve successfully saved and output data into an HTML file using a simple function in python. Any one of the above methods can be used to get the desired result.

RELATED ARTICLES

Most Popular

Recent Comments