46

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>
12
  • Out of interest, what number are you expecting len(s) to be?
    – Tom
    May 13, 2013 at 14:03
  • 1
    What's wrong with html_file.write(<td><font style="background-color:%s;">%s<font></td>' % (colour[j % len(colour)], k)) etc?
    – timss
    May 13, 2013 at 14:03
  • Also, you're mixing print "string" and print("string"). Stick with the one that is default in the python version you're using.
    – timss
    May 13, 2013 at 14:05
  • 1
    @MichaelW I haven't leant DOM. How to use it btw? May 13, 2013 at 14:16
  • 1
    I understood you. You can have multi-line strings by putting them in triple quotes: """ long string goes here """. So just store your HTML in a string variable: html_str = """long html string""". Then pass that variable to write: HTML_file.write(html_str). Does that help?
    – Anubhav C
    May 13, 2013 at 15:28

6 Answers 6

77

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()
27

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.

1
  • 2
    I believe the with statement is preferred as you have less chance of a race condition, since the file is closed as soon as the write statement finishes (as opposed to closing the file descriptor manually with file.close()) Sep 17, 2021 at 14:37
4
print('<tr><td>%04d</td>' % (i+1), file=Html_file)
2
  • 4
    This will only work in using the python 3 print function, so you'd need to add from __future__ import print_function to use it with the python 2 code written in the question. May 13, 2013 at 14:07
  • Interesting! Is this in any way better than file.write()? Even if this is available, shouldn't you stick with the one, "preferred" way, file.write()?
    – timss
    May 13, 2013 at 14:08
2

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

with open("my.html","w") as fp:
   fp.write(html)
1

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>')
4
  • 1
    I'm not sure how optimized Python's file.write() is, but it strikes me as a bad idea to use it every time you want to append something, and that you should probably save it to a list (stack) before doing the IO. In other words have a content = [] and do content.extend("<html>") etc.
    – timss
    May 13, 2013 at 14:12
  • You can use itertools.cycle to simplify the background colour selection. e.g. create iterator using colour = itertools.cycle(["red", ...]) then use next(colour) to retrieve the next colour.
    – Shawn Chin
    May 13, 2013 at 14:13
  • This is going to write a file that is one line long since there are no line-breaks output anywhere. That's really long codes...
    – martineau
    May 13, 2013 at 14:15
  • 1
    Python's file.write() is buffered, so I wouldn 't worry about calling it a lot or trying to optimize calls to it.
    – martineau
    May 13, 2013 at 14:16
0

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()

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.