Created
May 11, 2017 15:14
-
-
Save keshavbahadoor/68c0f33152227be41a5bed51c0ef41ac to your computer and use it in GitHub Desktop.
Convert SQL Query to CSV File in Python
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
# Generic reader method | |
# Reads data, prints columns, and prints each row to file | |
def do_query_to_csv_file(cursor, sql, csv_file): | |
try: | |
cursor.execute(sql) | |
file_header = '' | |
f = open(file_dir + csv_file + '.csv', 'w') | |
columns = [column[0] for column in cursor.description] | |
for col in columns: | |
file_header = file_header + col + ',' | |
f.write(file_header[:-1] + '\n') | |
for row in cursor: | |
file_row = '' | |
for element in row: | |
if element is None: | |
element = '' | |
file_row = file_row + element.__str__().replace(',', ' ') + ',' | |
f.write(file_row[:-1] + '\n') | |
f.close() | |
print 'report completed: {}'.format(csv_file) | |
except Exception, e: | |
print e |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I actually can't remember what I was using this for, but it was Python 2.