How to import html file into python variable?
18,959
Solution 1
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()
Solution 2
Just open the file as in any I/O.
with open('test.html', 'r') as f:
html_string = f.read()
Author by
HunterLiu
www.infinity2o.com: Connect people with similar beliefs to take online courses together.
Updated on June 18, 2022Comments
-
HunterLiu almost 2 years
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> """