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
Python3 How do I send Pandas Dataframe in an email
提问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_html
feature.
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, df
defined as textfile
is data that exists in current memory. Therefore, the with open
command can not be executed. with open
is a function that loads any file stored on the hard disk into memory.
在上面的代码中,df
定义为textfile
当前内存中存在的数据。因此,该with open
命令无法执行。with open
是一种将存储在硬盘上的任何文件加载到内存中的函数。