【问题标题】:How to write and save html file in python?如何在python中编写和保存html文件?
【发布时间】:2013-05-07 14:21:37
【问题描述】:

这就是我对写入 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>

【问题讨论】:

  • 出于兴趣,您希望 len(s) 是多少?
  • html_file.write(&lt;td&gt;&lt;font style="background-color:%s;"&gt;%s&lt;font&gt;&lt;/td&gt;' % (colour[j % len(colour)], k)) 等有什么问题?
  • 另外,你正在混合print "string"print("string")。坚持使用您正在使用的 python 版本中的默认版本。
  • @MichaelW 我没有学习过 DOM。顺便说一句怎么用?
  • 我理解你。您可以将多行字符串放在三引号中:""" long string goes here """。因此,只需将您的 HTML 存储在一个字符串变量中:html_str = """long html string"""。然后将该变量传递给writeHTML_file.write(html_str)。这有帮助吗?

标签: python


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    正如其他人所提到的,对多行字符串使用三引号 ”””abc”””。此外,您无需使用 with 关键字调用 close() 即可执行此操作。据我所知,这是最佳实践(见下面的评论)。例如:

    # 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

    【讨论】:

    • 我相信 with 语句是首选的,因为您出现竞争条件的机会较小,因为文件在 write 语句完成后立即关闭(而不是使用 @ 手动关闭文件描述符987654328@)
    【解决方案3】:
    print('<tr><td>%04d</td>' % (i+1), file=Html_file)
    

    【讨论】:

    • 这仅适用于使用 python 3 打印功能,因此您需要添加 from __future__ import print_function 以将其与问题中编写的 python 2 代码一起使用。
    • 有趣!这比file.write()好吗?即使这是可用的,您不应该坚持一种“首选”方式file.write()吗?
    【解决方案4】:

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

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

    【讨论】:

      【解决方案5】:

      你可以试试:

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

      【讨论】:

      • 我不确定 Python 的 file.write() 的优化程度如何,但我觉得每次你想附加一些东西时都使用它是个坏主意,你应该把它保存到一个列表中(堆栈)在执行 IO 之前。换句话说,有content = []content.extend("&lt;html&gt;") 等。
      • 您可以使用itertools.cycle 来简化背景颜色的选择。例如使用colour = itertools.cycle(["red", ...]) 创建迭代器,然后使用next(colour) 检索下一个颜色。
      • 这将写入一个只有一行长的文件,因为任何地方都没有换行符输出。代码真的很长……
      • Python 的 file.write() 是缓冲的,所以我不用担心会经常调用它或尝试优化对它的调用。
      【解决方案6】:

      你可以使用 write() :

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-02-12
        • 2016-11-18
        • 1970-01-01
        • 2016-02-04
        • 2015-07-29
        • 1970-01-01
        • 1970-01-01
        • 2021-02-09
        相关资源
        最近更新 更多