Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby-on-rails-4/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
有没有一种方法可以在python中一次向文件写入几行代码?_Python_Writetofile - Fatal编程技术网

有没有一种方法可以在python中一次向文件写入几行代码?

有没有一种方法可以在python中一次向文件写入几行代码?,python,writetofile,Python,Writetofile,我需要将大量信息写入一个文件,基本上是一个完整的网页,其中包含使用脚本计算的特定值。我知道我可以使用.write来实现这一点,但是我想知道您是否可以一次将多行写入一个文件,而不必输入所有的换行符 例如,我想将以下内容添加到一个文件中: <!DOCTYPE html> <html> <head> </head> <style> some styling stuff .. <\style> <body> many m

我需要将大量信息写入一个文件,基本上是一个完整的网页,其中包含使用脚本计算的特定值。我知道我可以使用.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>')

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

使用三重引号时,会将换行符读入字符串:

file.write('''
<html>
<head>
</head>
<style>
some styling stuff ..
<\style>
<body>
many more lines of code ...
</body>
</html>''')
这就是file.writelines的用途:

您也可以使用带有三个引号或的多行字符串,但它们往往会弄乱缩进


以上所说的,考虑使用HTML输出。< /P>谷歌搜索Python多行字符串给出了一些很好的结果。如果您正在编写大型HTML文件,请考虑使用模板

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