Currently i am writing query in python which export data from oracle dbo to .csv file. I am not sure how to write headers within file.
try:
connection = cx_Oracle.connect('user','pass','tns_name')
cursor = connection.cursor()
print "connected"
try:
query = """select * from """ .format(line_name)
tmp = cursor.execute(query)
results = tmp.fetchall()
except:
pass
except:
print IOError
filename='{0}.csv'.format(line_name)
csv_file = open(filename,'wb')
if results:
myFile = csv.writer(csv_file)
myFile.writerows(results)
else:
print "null"
csv_file.close()
How do I put a header in a CSV file? If your CSV file doesn't have headers, you can add them by simply creating a new first line in the text file and typing in your headers.
You can create headings by starting and ending a line with up to five equal signs. The heading text is between those markers, separated by a single space.
CSV and spreadsheet content rules. Each row in the file must contain the same number of cells. This rule also applies to the header row. The first row must contain column headers.
you can ethier do this after executing your query:
columns = [i[0] for i in cursor.description]
so you get
query = """select * from """ .format(line_name)
tmp = cursor.execute(query)
columns = [i[0] for i in cursor.description]
results = tmp.fetchall()
and then do:
if results:
myFile = csv.writer(csv_file)
myFile.writerow(columns)
myFile.writerows(results)
or you can convert result to a dictionary and use DictWriter witch accepts fieldnames
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With