如何在python中编写和保存html文件?

时间:2013-05-13 13:59:42

标签: python

这就是我所知道的如何编写和保存它

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>

6 个答案:

答案 0 :(得分:47)

您可以通过将它们括在三引号中来创建多行字符串。因此,您可以将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()

答案 1 :(得分:4)

您也可以执行此操作,而无需使用close()关键字致电with。例如:

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

有关Python中with关键字的详细信息,请参阅https://stackoverflow.com/a/11783672/2206251

答案 2 :(得分:3)

print('<tr><td>%04d</td>' % (i+1), file=Html_file)

答案 3 :(得分:2)

您可以尝试:

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 :(得分:0)

您可以使用 write()

进行操作
#open file with *.html* extension to write html
file= open("my.html","w")
#write then close file
file.write(html)
file.close()

答案 5 :(得分:-1)

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

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