簡體   English   中英

不使用將 Pandas Dataframe as.csv 附加到 email 中。

[英]Attach Pandas Dataframe as .csv in email Without using .to_csv

我有一個 pandas 數據幀,我想在 email 附件中作為 .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()

並傳入字節緩沖區

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM