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?
mechanical_meat
  • 144,326
  • 21
  • 211
  • 203
trktel
  • 1

1 Answers1

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.
Community
  • 1
  • 1
Andy
  • 43,170
  • 54
  • 150
  • 214