How to write and save html file in python?

Question:

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>
Asked By: Erika Sawajiri

||

Answers:

print('<tr><td>%04d</td>' % (i+1), file=Html_file)
Answered By: GWW

You can try:

colour = ["red", "red", "green", "yellow"]

with open('mypage.html', 'w') as myFile:
    myFile.write('<html>')
    myFile.write('<body>')
    myFile.write('<table>')

    s = '1234567890'
    for i in range(0, len(s), 60):
        myFile.write('<tr><td>%04d</td>' % (i+1));
    for j, k in enumerate(s[i:i+60]):
        myFile.write('<td><font style="background-color:%s;">%s<font></td>' % (colour[j %len(colour)], k));


    myFile.write('</tr>')
    myFile.write('</table>')
    myFile.write('</body>')
    myFile.write('</html>')
Answered By: Igo Coelho

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()
Answered By: Anubhav C

You can do it using write() :

#open file with *.html* extension to write html
file= open("my.html","w")
#write then close file
file.write(html)
file.close()
Answered By: Nurul Akter Towhid

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.

Answered By: Greenstick

shorter version of Nurul Akter Towhid’s answer (the fp.close is automated):

with open("my.html","w") as fp:
   fp.write(html)
Answered By: mousomer
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.