如何在Python写入 HTML 文件?
Python语言如今几乎在每个领域都有很大的用途,它可以与其他技术一起使用,让我们的生活更轻松。 Python 的一种这样的用法是在 HTML 文件中获取数据输出。
我们可以通过以下两种方式使用以下示例将任意数量的输入数据保存到Python的 HTML 文件中。
示例 1:创建一个 HTML 文件并将输入数据保存到其中。
方法:
- 创建 HTML 文件。
Function_Name = open("Complete_File_Name","File_operation")
- 将 HTML 格式的输入数据添加到文件中。
Function_Name.write("Adding_Input_data_using_HTML_Synatx_separted_by_/n")
- 保存 HTML 文件。
Function_Name.close()
- 从保存的位置打开 HTML 文件。
下面是实现:
Python3
# Creating an HTML file
Func = open("GFG-1.html","w")
# Adding input data to the HTML file
Func.write("\n\n \nOutput Data in an HTML file \
\n Welcome to GeeksforGeeks
\
\nA CS Portal for Everyone
\n")
# Saving the data into the HTML file
Func.close()
Python3
# Opening the existing HTML file
Func = open("GFG-2.html","w")
# Adding input data to the HTML file
Func.write("\n\n \nOutput Data in an HTML file\n \
\n Welcome to \
GeeksforGeeks
\n \
A CS Portal for Everyone
\n")
# Saving the data into the HTML file
Func.close()
输出:

在文件夹中创建GFG-1.html文件

检查GFG-1.html文件的输出数据
示例 2:创建并保存 HTML 文件,然后向其中添加输入数据。
方法:
- 创建一个 HTML 文件并保存它。
Function_Name = open("Complete_File_Name","File_operation")
Function_Name.close()
- 从保存的位置打开 HTML 文件。
- 现在将输入数据添加到创建的 HTML 文件中。
Function_Name = open(File_Location,"File_operation")
Function_Name.write("Adding_Input_data_using_HTML_Synatx_separted_by_/n")
- 保存 HTML 文件。
Function_Name.close()
- 再次从保存位置打开 HTML 文件以检查输出数据。
下面是实现:
蟒蛇3
# Opening the existing HTML file
Func = open("GFG-2.html","w")
# Adding input data to the HTML file
Func.write("\n\n \nOutput Data in an HTML file\n \
\n Welcome to \
GeeksforGeeks
\n \
A CS Portal for Everyone
\n")
# Saving the data into the HTML file
Func.close()
输出:

输入数据保存到GFG-2.html文件中

检查GFG-2.html文件的输出数据
我们已经使用Python的一个简单函数成功地将数据保存并输出到一个HTML文件中。可以使用上述任何一种方法来获得所需的结果。