Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write and save html file in python?

Tags:

python

This is what I know about writing to an HTML file and saving it:

html_file = open("filename","w") html_file.write() html_file.close() 

But how do I save to the file if I want to write a really long codes like this:

   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> 
like image 320
Erika Sawajiri Avatar asked May 13 '13 13:05

Erika Sawajiri


People also ask

How do I save a webpage in Python?

To save a page we shall first obtain the page source behind the webpage with the help of the page_source method. We shall open a file with a particular encoding with the codecs. open method. The file has to be opened in the write mode represented by w and encoding type as utf−8.

Can we code HTML in Python?

“Hello World” in HTML using Python It is possible, in other words, to write programs that manipulate other programs. What we're going to do next is create an HTML file that says “Hello World!” using Python. We will do this by storing HTML tags in a multiline Python string and saving the contents to a new file.


2 Answers

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() 
like image 72
Anubhav C Avatar answered Sep 24 '22 10:09

Anubhav C


As others have mentioned, use triple quotes ”””abc””” for multiline strings. Also, you can do this without having to call close() using the with keyword. This is, to my knowledge, best practice (see comment below). 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.

like image 36
Greenstick Avatar answered Sep 26 '22 10:09

Greenstick