Search code examples
pythonwritetofile

Is there a way of writing several lines at a time to a file in python?


I need to write a lot of information to a file, basically a whole webpage with certain values calculated using my script. I know I can do this using .write(), however I would like to know if you can write several lines at a time to a file, without having to put in all of the line breaks.

For example, I would like to wite the following to a file:

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

Currently I have

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

But I would like to be able to do

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

Does anybody know of a way to do this? Thanks!


Solution

  • When you use triple quotes ('''), line breaks are read into the string:

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