How to write and save html file in python?

前端 未结 6 2205
挽巷
挽巷 2020-12-05 02:22

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

相关标签:
6条回答
  • 2020-12-05 02:38

    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>')
    
    0 讨论(0)
  • 2020-12-05 02:40

    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()
    
    0 讨论(0)
  • 2020-12-05 02:43

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

    with open("my.html","w") as fp:
       fp.write(html)
    
    0 讨论(0)
  • 2020-12-05 02:49
    print('<tr><td>%04d</td>' % (i+1), file=Html_file)
    
    0 讨论(0)
  • 2020-12-05 02:56

    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.

    0 讨论(0)
  • 2020-12-05 03:04

    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()
    
    0 讨论(0)
提交回复
热议问题