2020年3月10日 星期二

python to_txt

import pyodbc
import pandas as pd # 引用套件並縮寫為 pd

cnxn = pyodbc.connect("DRIVER={MySQL ODBC 8.0 Unicode Driver}; SERVER=localhost; PORT=3306;DATABASE=my_db; UID=root; PASSWORD=gimy0710;OPTION=3;CHARSET=UTF8;")
SQL = "SELECT * FROM expense where PAY_DATE > '2020/1/1' order by PAY_DATE desc"
file_name = "test.txt"

df = pd.read_sql(SQL, cnxn)
cnxn.close()

txt = ""
for row in df.columns:
    txt = txt + row + "|"
txt = txt + "\n"

for row in df.values:
    for i in range(0,len(row)):
        txt = txt + str(row[i]) + "|"
    txt = txt + "\n"
#print(txt)
f = open(file_name,'w')
f.write(txt)
f.close()

沒有留言:

張貼留言