This is what I know about writing to an HTML file and saving it:
html_file = open("filename","w") html_file.write() html_file.close()
But how do I save to the file if I want to write a really long codes like this:
1 <table border=1> 2 <tr> 3 <th>Number</th> 4 <th>Square</th> 5 </tr> 6 <indent> 7 <% for i in range(10): %> 8 <tr> 9 <td><%= i %></td> 10 <td><%= i**2 %></td> 11 </tr> 12 </indent> 13 </table>
To save a page we shall first obtain the page source behind the webpage with the help of the page_source method. We shall open a file with a particular encoding with the codecs. open method. The file has to be opened in the write mode represented by w and encoding type as utf−8.
“Hello World” in HTML using Python It is possible, in other words, to write programs that manipulate other programs. What we're going to do next is create an HTML file that says “Hello World!” using Python. We will do this by storing HTML tags in a multiline Python string and saving the contents to a new file.
You can create multi-line strings by enclosing them in triple quotes. So you can store your HTML in a string and pass that string to write()
:
html_str = """ <table border=1> <tr> <th>Number</th> <th>Square</th> </tr> <indent> <% for i in range(10): %> <tr> <td><%= i %></td> <td><%= i**2 %></td> </tr> </indent> </table> """ Html_file= open("filename","w") Html_file.write(html_str) Html_file.close()
As others have mentioned, use triple quotes ”””abc”””
for multiline strings. Also, you can do this without having to call close()
using the with
keyword. This is, to my knowledge, best practice (see comment below). For example:
# HTML String html = """ <table border=1> <tr> <th>Number</th> <th>Square</th> </tr> <indent> <% for i in range(10): %> <tr> <td><%= i %></td> <td><%= i**2 %></td> </tr> </indent> </table> """ # Write HTML String to file.html with open("file.html", "w") as file: file.write(html)
See https://stackoverflow.com/a/11783672/2206251 for more details on the with
keyword in Python.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With