This is what I know how to write and save it
Html_file= open\"(filename\",\"w\")
Html_file.write()
Html_file.close
But how do I save to the
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>')
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()
shorter version of Nurul Akter Towhid's answer (the fp.close is automated):
with open("my.html","w") as fp:
fp.write(html)
print('<tr><td>%04d</td>' % (i+1), file=Html_file)
You can also do this without having to call close()
using the with
keyword. 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.
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()