Skip to content

Instantly share code, notes, and snippets.

@keshavbahadoor
Created May 11, 2017 15:14
Show Gist options
  • Save keshavbahadoor/68c0f33152227be41a5bed51c0ef41ac to your computer and use it in GitHub Desktop.
Save keshavbahadoor/68c0f33152227be41a5bed51c0ef41ac to your computer and use it in GitHub Desktop.
Convert SQL Query to CSV File in Python
# 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
@michaelaffare
Copy link

thanks, really helpful.

PS: check print commands. in python3 print function works as print()

@keshavbahadoor
Copy link
Author

keshavbahadoor commented Jul 2, 2020

I actually can't remember what I was using this for, but it was Python 2.

@yashsoni27
Copy link

Can you also post the main function of this script as well? @keshavbahadoor
Thanks in advance!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment