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?
2
Answers
You can use
StringIO
from io, then pass the instance toDataFrame.to_csv
method:To read the object as file, you need to call
seek
passing0
to reset the cursor, then read the file:I use StringIO: