Created
June 22, 2009 22:41
-
-
Save thepaul/134233 to your computer and use it in GitHub Desktop.
export random database stuff to csv
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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