Python未将MS SQL存储过程中的所有数据行写入CSV

Python未将MS SQL存储过程中的所有数据行写入CSV,python,sql-server,Python,Sql Server,我正在编写一个脚本,该脚本将执行MS SQL存储过程,并将每一行写入CSV。它只输出SELECT语句的最后十行,对于最后一行,它只在前两列中有数据 # Importing the required libaries import pypyodbc import csv import win32com.client as win32 import time # Setting up the Connection to the SQL Server cnxn = pypyodbc.connect(

我正在编写一个脚本,该脚本将执行MS SQL存储过程,并将每一行写入CSV。它只输出SELECT语句的最后十行,对于最后一行,它只在前两列中有数据

# Importing the required libaries
import pypyodbc
import csv
import win32com.client as win32
import time

# Setting up the Connection to the SQL Server
cnxn = pypyodbc.connect("Driver= {SQL Server Native Client 11.0};"
                    "Server=sql2012;"
                    "Database=Client;"
                    "Trusted_Connection=yes;")

cursor = cnxn.cursor()
data = cursor.execute("EXEC usp_rpt_QuestionFile") #Running the SP and housing the data 
headers = [tuple[0] for tuple in data.description] # Getting the field names out of the SP
timestr = time.strftime("%Y%m%d") # Storing the current date
path = "Y:\Client Files\Client\Perpetual\Questions\Client QuestionsTest"+timestr+".csv" # Where the file will be saved
f = csv.writer(open(path, "wb"), delimiter=",")
f.writerow(headers) #Writing the field names as the first row to the CSV
for row in data: #Appending the data to the file
    f.writerow(row)


#Sending the email and attachment
outlook = win32.Dispatch('outlook.application')
mail = outlook.CreateItem(0)
mail.To = 'email@email.com'
mail.Subject = 'Subject'
mail.body = ''
attachment1 = path
mail.Attachments.Add(Source=attachment1)
mail.send

Y驱动器上的输出文件中缺少数据,还是仅在电子邮件副本中缺少数据?如果是后者,看起来您需要关闭输出文件,以便在将其复制到电子邮件之前刷新缓冲区。 最好的方法是将
语句一起使用:

with open(path, "wb") as f:
    wtr = csv.writer(f, delimiter=",")
    wtr.writerow(headers) #Writing the field names as the first row to the CSV
    wtr.writerows(data)

打印到屏幕或其他位置时,SP返回的所有预期行是否都存在?这非常完美。谢谢