简体   繁体   中英

how do i send emsil csv attachment with python pandas without exporting to csv file ithut using to_csv

I got the below script to work to export to csv file by reading it from mysql table. But I need this csv attachment not to save to local. instead attach it in email and send it

any idea?

import pandas as pd
import pymysql
from sqlalchemy import create_engine
from urllib.parse import quote
import smtplib


username = "root"
password = "xxxxxx"
port = 3306
database = "DB"


engine = create_engine('mysql+pymysql://root:%s@hostname:3306/DB' % quote('xxxxxx'))

sql_query = pd.read_sql(SELECT * FROM table, engine)

print(sql_query)
df = pd.DataFrame(sql_query)
df.to_csv (r'localpath/filename.csv', index = False)

any idea?

You can use StringIO from io, then pass the instance to DataFrame.to_csv method:

>>> from io import StringIO
>>> csv_file = StringIO()
>>> df.to_csv(csv_file)

To read the object as file, you need to call seek passing 0 to reset the cursor, then read the file:

>>> csv.seek(0)
>>> pd.read_csv(csv_file)
   Unnamed: 0  Heading1 Heading2
0           0         1     0994
1           1         2     113G
2           2         3     113N
3           3         4     0978

I use StringIO:

from io import StringIO


def create_csv(df: pd.DataFrame) -> str:
    with StringIO() as buffer:
        df.to_csv(buffer, index=False)

        return buffer.getvalue()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM