【问题标题】:Is there a way of writing several lines at a time to a file in python?有没有办法一次将多行写入python中的文件?
【发布时间】:2014-09-11 14:20:19
【问题描述】:

我需要将大量信息写入文件,基本上是整个网页,其中包含使用我的脚本计算的某些值。我知道我可以使用 .write() 来做到这一点,但是我想知道您是否可以一次将多行写入一个文件,而不必放入所有换行符。

例如,我想将以下内容写入文件:

<!DOCTYPE html>
<html>
<head>
</head>
<style>
some styling stuff ..
<\style>
<body>
many more lines of code ...
</body>
</html>

目前我有

file = open('filetowriteto.txt','w')
file.write('<html>\n')
file.write('<head>\n')
...
file.close()

但我希望能够做到

file.write('
<html>
<head>
</head>
<style>
some styling stuff ..
<\style>
<body>
many more lines of code ...
</body>
</html>')

有人知道这样做的方法吗?谢谢!

【问题讨论】:

  • “Python 多行字符串”的 Google 搜索给出了一些不错的结果。 :)
  • 如果您正在编写大型 HTML 文件,请查看使用 templates

标签: python writetofile


【解决方案1】:

当您使用三引号 (''') 时,会将换行符读入字符串:

file.write('''
<html>
<head>
</head>
<style>
some styling stuff ..
<\style>
<body>
many more lines of code ...
</body>
</html>''')

【讨论】:

    【解决方案2】:

    这就是file.writelines 的用途:

    with open(filename) as fp:
        fp.writelines([
            '<html>',
            '</html>'
        ])
    

    您也可以使用带有三引号 '''""" 的多行字符串,但它们往往会与缩进混淆。

    话虽如此,请考虑将Jinja 用于 HTML 输出。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-01
      • 1970-01-01
      • 2019-09-20
      • 1970-01-01
      • 2019-02-11
      相关资源
      最近更新 更多