使用pymssql写入CSV并使用列名作为标题

时间:2017-07-20 17:52:25

标签: python csv export-to-csv pymssql

我有以下脚本:i)连接数据库,ii)运行查询,iii)将查询结果保存为csv,iv)通过电子邮件发送输出。

一切正常,但我似乎无法将列名称作为文件头。我已经通过搜索引擎优化,但无法找到适合我的解决方案。我的脚本如下。任何帮助都会很棒:

import pymssql
import csv
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email import encoders
fromaddr='XXXX@gmail.com'
toaddr='XXXX@gmail.com'
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = "This is a test"
body = "This is still a test"
conn = pymssql.connect(server='XXXXXXXXXX.net',
               port=XXXX,
               user='XXXX',
               password='XXXX',
               database='XXXX')
cursor = conn.cursor()
query = 'Select * From Table'
cursor.execute(query)
with open("XXXXXXXX.csv","w") as outfile:
    writer = csv.writer(outfile, quoting=csv.QUOTE_NONNUMERIC)
    for row in cursor:
        writer.writerow(row)
msg.attach(MIMEText(body,'plain'))
filename = "XXXXXX.csv"
attachment = open("XXXXXXXXXXX.csv","rb")
from email.mime.base import MIMEBase
part = MIMEBase('application','octet-stream')
part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header('Content-Disposition',"attachment; filename= %s" % filename)
msg.attach(part)
text = msg.as_string()
server = smtplib.SMTP('smtp.office365.com',587)
server.starttls()
server.login(fromaddr,"XXXXXX")
text = msg.as_string()
server.sendmail(fromaddr,toaddr,text)

2 个答案:

答案 0 :(得分:3)

根据DB-API - PyMSSQL complies - 有一个名为.description的游标属性,您可以在这里使用。

with open("XXXXXXXX.csv","w") as outfile:
    writer = csv.writer(outfile, quoting=csv.QUOTE_NONNUMERIC)
    writer.writerow(col[0] for col in cursor.description)
    for row in cursor:
        writer.writerow(row)

答案 1 :(得分:0)

使用.description对象上的cursor并遍历它以获取列的名称,如:

colNameList = []
for i in range(len(cursor.description)):
    desc = cursor.description[i]
    colNameList.append(desc[0])

    colNames = ','.join(colNameList)
    print colNames