Python - write headers to csv
Asked Answered
H

1

6

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()
Homan answered 12/9, 2015 at 8:40 Comment(0)
A
13

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

Acridine answered 12/9, 2015 at 9:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.