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>
daudprobst
  • 132
  • 8
Erika Sawajiri
  • 1,136
  • 3
  • 13
  • 18
  • Out of interest, what number are you expecting len(s) to be? – Tom May 13 '13 at 14:03
  • 1
    What's wrong with `html_file.write(%s' % (colour[j % len(colour)], k))` etc? – timss May 13 '13 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 '13 at 14:05
  • Really long codes are fine, but you do realize that you can insert whitespace very freely in html lf you desire, don't you? – martineau May 13 '13 at 14:10
  • Why don't you use a library for DOM manipulation? – Michael W May 13 '13 at 14:12
  • 1
    @MichaelW I haven't leant DOM. How to use it btw? – Erika Sawajiri May 13 '13 at 14:16
  • @ErikaSawajiri I don't think anyone can understand what you're asking. Changing the example just causes further confusion. What do you mean by "long codes"? Do you mean (A) HTML containing many lines, or (B) HTML generated using Python code (e.g. `for` loops)? – Anubhav C May 13 '13 at 14:53
  • @Anubhav I mean it is vey long so how do I put it to the html_write() function that usually just take one or two words inside the brackets. Sorry I know my english isn't that good but I really tried to explain it. Moreover,I'm still beginner in python but I really want to learn so I can be as good as you guys – Erika Sawajiri May 13 '13 at 15:20
  • 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 '13 at 15:28
  • I'll post it as an answer. Please accept it, so the question doesn't show up in the "unanswered" section. – Anubhav C May 13 '13 at 15:34
  • Possible duplicate of [Python Print String To Text File](https://stackoverflow.com/questions/5214578/python-print-string-to-text-file) – Andreas is moving to Codidact Oct 06 '19 at 22:20
  • Does this answer your question? [Pythonic way to create a long multi-line string](https://stackoverflow.com/questions/10660435/pythonic-way-to-create-a-long-multi-line-string) – Andreas is moving to Codidact Dec 08 '19 at 21:27

6 Answers6

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()
Anubhav C
  • 2,631
  • 2
  • 18
  • 23
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.

Greenstick
  • 8,632
  • 1
  • 24
  • 29
  • 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()`) – oneindelijk Sep 17 '21 at 14:37
4
print('<tr><td>%04d</td>' % (i+1), file=Html_file)
GWW
  • 43,129
  • 11
  • 115
  • 108
  • 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. – Dave Challis May 13 '13 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 '13 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)
mousomer
  • 2,632
  • 2
  • 24
  • 25
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>')
Igo Coelho
  • 47
  • 5
  • 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("")` etc. – timss May 13 '13 at 14:12
  • You can use [itertools.cycle](http://docs.python.org/2/library/itertools.html#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 '13 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 '13 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 '13 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()
Nurul Akter Towhid
  • 3,046
  • 2
  • 33
  • 35