Home > front end >  how do i send emsil csv attachment with python pandas without exporting to csv file ithut using to_c
how do i send emsil csv attachment with python pandas without exporting to csv file ithut using to_c

Time:09-20

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?

CodePudding user response:

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

CodePudding user response:

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()
  • Related