Printing mutiple HTML tables using tabulate in python

旧时模样 提交于 2019-12-14 03:24:05

问题


I want to produce two HTML tables using tabulate package, but I am only able to produce one table and send mail.

Is it possible to put more than one html table into a message sent with smtplib and email? Whenever I use attach() for more than one thing, it only adds the first.

text = """
Hello, Friend.

Here is your data:

{table}

Regards,

Me
"""

html = """
<html>
<body>
    <p>Hello, Friend.</p>
    <p>Here is your data:</p>
    {table}
    <p>Regards,</p>
    <p>Me</p>
</body>
</html>
"""

with open('input.csv') as input_file:
    reader = csv.reader(input_file)
    data = list(reader)

    text = text.format(table=tabulate(data, headers="firstrow", tablefmt="grid"))
    html = html.format(table=tabulate(data, headers="firstrow", tablefmt="html"))

    message = MIMEMultipart(
       "alternative", None, [MIMEText(text), MIMEText(html,'html')]
    )

回答1:


Yes. First you have to change the number of fields you want to substitute as tables:

text = """ [...] {table1} {table2} [...] """

Then you have to pass the content to format as kwargs:

text = text.format(table1=tabulate(data, headers="firstrow", tablefmt="grid"),
                   table2=your_new_table_tabulation)

Same you can do for html

String formatting in Python is no sort of attachment, but rather a substitution of content into a pre-formatted field. You can substitute as many fields as you'd like, putting the names you'd like, and with the content you'd like. Then, when you send the email, you will send a normal HTML file with the tables rendered into as HTML/text

I encourage you to check out: https://docs.python.org/3/library/string.html#string.Formatter.format

That is for Python's version 3.7. You have almost every Python's version available online.



来源:https://stackoverflow.com/questions/51930239/printing-mutiple-html-tables-using-tabulate-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!