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? Commented 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? Commented 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. Commented May 13, 2013 at 14:05
  • 1
    @MichaelW I haven't leant DOM. How to use it btw? Commented 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? Commented May 13, 2013 at 15:28

6 Answers 6

78

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()
Sign up to request clarification or add additional context in comments.

Comments

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 Comment

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())
4
print('<tr><td>%04d</td>' % (i+1), file=Html_file)

2 Comments

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.
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()?
3

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

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

Comments

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 Comments

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.
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.
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...
Python's file.write() is buffered, so I wouldn 't worry about calling it a lot or trying to optimize calls to it.
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()

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.