Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - write headers to csv

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()
like image 576
Wiktor Avatar asked Sep 12 '15 08:09

Wiktor


People also ask

How do I assign a header to a CSV file?

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.

How do I make a header in Python?

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.

Can CSV files have headers?

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.


1 Answers

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

like image 194
DorElias Avatar answered Nov 15 '22 07:11

DorElias