Samsquanch
Samsquanch

Reputation: 9146

Append columns to python cursor before writing to CSV?

#!/usr/bin/env python
import csv
import pyodbc

out_file = "file.csv"

conn = pyodbc.connect("DRIVER={driver};SERVER=servername;UID=user;PWD=pass;DATABASE=data")

cursor = conn.execute("SELECT TOP 10 * FROM table")

with open(out_file, 'w') as f:
  print cursor
  csv.writer(f, quoting=csv.QUOTE_MINIMAL).writerows(cursor)

That is my code as of now, and that works as expected. My question is, how would I add a few null-valued columns to the row before inserting it into the CSV? I need to do this because I'll be combining it with another query that is going to have a few extra data columns and I'd like the data to line up with null-filled columns.

Upvotes: 0

Views: 1072

Answers (1)

Mark Ransom
Mark Ransom

Reputation: 308216

How about:

writer = csv.writer(f, quoting=csv.QUOTE_MINIMAL)
for row in cursor:
    writer.writerow(list(row) + ['', '', '', ''])

Upvotes: 2

Related Questions