Python3 如何在电子邮件中发送 Pandas Dataframe

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48196273/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 05:02:38  来源:igfitidea点击:

Python3 How do I send Pandas Dataframe in an email

pandasdataframe

提问by user3613102

def call_panda():
    filename = 'C:\file.csv'
    cols_to_use = ['col1', 'col2', 'col3', 'col4']
    df = pd.read_csv(filename, nrows= 5,usecols=cols_to_use,index_col='col1')               
    # Send email
    me = '[email protected]'
    you = '[email protected]'
    textfile = df
    with open(textfile, 'rb') as fp:
        msg = MIMEText(fp.read())
        msg['Subject'] = 'Contents of file'
        msg['From'] = me
        msg['To'] = you
        s = smtplib.SMTP('mailhost.acme.net')
        s.sendmail(me, [you], msg.as_string())
        s.quit()

Error Message is with open(textfile, 'rb') as fp: TypeError: expected str, bytes or os.PathLike object, not DataFrame

错误消息是 open(textfile, 'rb') as fp: TypeError: expected str, bytes or os.PathLike object, not DataFrame

回答by Evan

Pandas has a df.to_htmlfeature.

Pandas有一个df.to_html特点。

https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_html.html

https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_html.html

Copying Chris Albon: https://chrisalbon.com/python/data_wrangling/pandas_join_merge_dataframe/

复制 Chris Albon:https: //chrisalbon.com/python/data_wrangling/pandas_join_merge_dataframe/

import pandas as pd

raw_data = {
        'subject_id': ['1', '2', '3', '4', '5'],
        'first_name': ['Alex', 'Amy', 'Allen', 'Alice', 'Ayoung'], 
        'last_name': ['Anderson', 'Ackerman', 'Ali', 'Aoni', 'Atiches']}
df_a = pd.DataFrame(raw_data, columns = ['subject_id', 'first_name', 'last_name'])
df_a.to_html('df.html')

From here, check this thread for email tips: Sending HTML email using Python

从这里,查看此线程以获取电子邮件提示:使用 Python 发送 HTML 电子邮件

It looks like you'll need to attach the HTML file; I'm not sure if it'll display online, and I don't have a mail server with which I can check.

看起来您需要附加 HTML 文件;我不确定它是否会在线显示,而且我没有可以检查的邮件服务器。

回答by Cho

In the above code, dfdefined as textfileis data that exists in current memory. Therefore, the with opencommand can not be executed. with openis a function that loads any file stored on the hard disk into memory.

在上面的代码中,df定义为textfile当前内存中存在的数据。因此,该with open命令无法执行。with open是一种将存储在硬盘上的任何文件加载到内存中的函数。