0

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?
1
  • 2
    You can use the csv module to write out the row. Commented Feb 4, 2015 at 18:50

1 Answer 1

1

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:

  • I open the file to write to only after the query has been run, instead of at the beginning of the program. Additionally I use the with statement to open the file.
  • Notice that the file name is a raw string (with the r, because the \s are escape characters.
  • The file mode needed to be quoted.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.