Reputation: 1
I am new to python. I can not figre out how to write a sql server table row to an output file. I can pt it on the screen but can't write it to a file.
import pyodbc
f.open(‘c:\python27\out.txt’,w)
cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=localhost;DATABASE=vzw;trusted_connection=True')
cursor = cnxn.cursor()
cursor.execute ("select * from vzw.dbo.threcord")
row = cursor.fetchall()
print row # displays row on screen
f.write #what goes here to indicate the displayed row?
Upvotes: 0
Views: 1022
Reputation: 50560
You can output to a comma separated file by utilizing the csv
module.
import pyodbc
import csv
cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=localhost;DATABASE=vzw;trusted_connection=True')
cursor = cnxn.cursor()
cursor.execute("select * from vzw.dbo.threcord")
row = cursor.fetchall()
with open(r"c:\python27\out.txt", "w") as f:
csv.writer(f).writerows(row)
A few notes about what I've changed from your code:
with
statement to open the file.r
, because the \
s are escape characters.Upvotes: 1