44

这就是我对写入 HTML 文件并保存它的了解:

html_file = open("filename","w")
html_file.write()
html_file.close()

但是如果我想写一个很长的代码,我该如何保存到文件中:

   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>
4

6 回答 6

75

您可以通过将它们括在三引号中来创建多行字符串。因此,您可以将 HTML 存储在一个字符串中并将该字符串传递给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()
于 2013-05-13T15:37:57.383 回答
26
于 2017-08-15T18:20:17.100 回答
4
print('<tr><td>%04d</td>' % (i+1), file=Html_file)
于 2013-05-13T14:02:52.047 回答
2

Nurul Akter Towhid 答案的较短版本(fp.close 是自动的):

with open("my.html","w") as fp:
   fp.write(html)
于 2018-06-21T08:09:43.037 回答
1

你可以试试:

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>')
于 2013-05-13T14:11:04.720 回答
0

您可以使用write() 来做到这一点:

#open file with *.html* extension to write html
file= open("my.html","w")
#write then close file
file.write(html)
file.close()
于 2017-07-31T01:11:35.270 回答