如何解决在不使用.to_csv的情况下将Pandas Dataframe作为.csv附加到电子邮件中
我有一个熊猫数据框,我想将其作为.csv文件发送到电子邮件附件中。因此,现在当我使用df.to_csv()时,每次都会下载文件。
我不想将文件保存在系统中,而只是想直接将其作为.csv文件传递。有办法吗?
import pandas as pd
df = pd.DataFrame(output of sqlquery) # this data is dataframe output of a sql query.
def send_email(sender,recipient,aws_region,subject,df):
client = boto3.client('ses',region_name=aws_region)
BODY_TEXT = "Hello,\r\nPlease find the attached file."
BODY_HTML = """\
<html>
<head></head>
<body>
<h1>Hello!</h1>
<p>Please find the attached file.</p>
</body>
</html>
"""
msg = MIMEMultipart('mixed')
msg['From'] = sender
print(msg['From'])
msg['To'] = recipient
msg['Subject'] = 'TOI Order Alert'
# The character encoding for the email.
CHARSET = "UTF-8"
msg_body = MIMEMultipart('alternative')
textpart = MIMEText(BODY_TEXT.encode(CHARSET),'plain',CHARSET)
htmlpart = MIMEText(BODY_HTML.encode(CHARSET),'html',CHARSET)
# Add the text and HTML parts to the child container.
msg_body.attach(textpart)
msg_body.attach(htmlpart)
# # Define the attachment part and encode it using MIMEApplication.
att = MIMEApplication(df.to_csv('test.csv'))
att.add_header('Content-Disposition','attachment; filename='+ 'test.csv')
# Attach the multipart/alternative child container to the multipart/mixed
# parent container.
msg.attach(msg_body)
# Add the attachment to the parent container.
msg.attach(att)
#Provide the contents of the email.
response = client.send_raw_email(
Source=msg['From'],Destinations=[
msg['To']
],RawMessage={
'Data':msg.as_string(),}
)
解决方法
我建议以下内容
import io
s_buf = io.StringIO()
df.to_csv(s_buf)
byte_buf = s_buf.encode()
并传入字节缓冲区
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。