Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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> """
like image 331
HunterLiu Avatar asked Aug 10 '18 22:08

HunterLiu


2 Answers

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()
like image 169
brandonwang Avatar answered Oct 17 '22 02:10

brandonwang


Just open the file as in any I/O.

with open('test.html', 'r') as f: 
        html_string = f.read()
like image 3
J. Blackadar Avatar answered Oct 17 '22 03:10

J. Blackadar