Skip to content

Instantly share code, notes, and snippets.

@thepaul
Created June 22, 2009 22:41
Show Gist options
  • Save thepaul/134233 to your computer and use it in GitHub Desktop.
Save thepaul/134233 to your computer and use it in GitHub Desktop.
export random database stuff to csv
# export2csv.py
#
# export random database stuff to csv
from __future__ import with_statement
import csv
def export2csv(cursor, outf):
"""
cursor should have an executed query already
outf should be a writeable file-like object
"""
writer = csv.writer(outf)
writer.writerow([d[0] for d in cursor.description])
while True:
row = cursor.fetchone()
if row is None:
break
row = [unicode(s).encode('utf-8') for s in row]
writer.writerow(row)
def export2csvfile(cursor, outfname):
with file(outfname, 'wb') as f:
return export2csv(cursor, f)
def table2csvfile(dbconn, tabname, outfname):
cursor = dbconn.cursor()
cursor.execute('select * from %s' % tabname)
ret = export2csvfile(cursor, outfname)
cursor.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment