HunterLiu
HunterLiu

Reputation: 801

How to import html file into python variable?

I'm trying to send an html email using python, MIMEMultipart, and smtp. The html is quite long, so I put all of the html in an html file. Now I want to import the html file into my python file (in the same folder) and set all of the html as a string in a python variable called html_string.

html:

<html>
    <head>
      <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
      <title>Welcome to infinity2o</title>
      <style type="text/css">
        body {
          padding-top: 0 !important;
          padding-bottom: 0 !important;
          padding-top: 0 !important;
          padding-bottom: 0 !important;
          margin: 0 !important;
          width: 100% !important;
          -webkit-text-size-adjust: 100% !important;
          -ms-text-size-adjust: 100% !important;
          -webkit-font-smoothing: antialiased !important;
        }
    .
    .
    .
    </head>
</html>

How do I import all of the html into my python file and set it equal to a variable:

python:

html_string = """
   <html>
        <head>
          <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
          <title>Welcome to infinity2o</title>
          <style type="text/css">
            body {
              padding-top: 0 !important;
              padding-bottom: 0 !important;
              padding-top: 0 !important;
              padding-bottom: 0 !important;
              margin: 0 !important;
              width: 100% !important;
              -webkit-text-size-adjust: 100% !important;
              -ms-text-size-adjust: 100% !important;
              -webkit-font-smoothing: antialiased !important;
            }
        .
        .
        .
        </head>
    </html> """

Upvotes: 10

Views: 39699

Answers (3)

Tiago Peres
Tiago Peres

Reputation: 15602

You can simply use the following

fname = "FILE.html"
html_file = open(fname, 'r', encoding='utf-8')
source_code = html_file.read() 
print(source_code)

and it'll print the entire .html file as you can see in the following screenshot taken in Spyder

enter image description here

Upvotes: 3

J. Blackadar
J. Blackadar

Reputation: 1961

Just open the file as in any I/O.

with open('test.html', 'r') as f: 
        html_string = f.read()

Upvotes: 3

brandonwang
brandonwang

Reputation: 1653

You can open the file, read all its contents, and set it equal to a variable:

with open('html_file.html', 'r') as f:
    html_string = f.read()

Upvotes: 32

Related Questions