royskatt
royskatt

Reputation: 1210

Python - cx_oracle print variable amount of column names

Based on a given SQL-Statement, I extract from a database to CSV with thefollowing function:

def extract_from_db():
    with open('myfile.csv','w') as outfile:
        for row in cursor:
            outfile.write(str(row[0])+";"+str(row[1])+";"+str(row[2])+";"+str(row[3])+";"+str(row[4])+";"+str(row[5])
               +";"+str(row[6])+";"+str(row[7])+";"+str(row[8])+";"+str(row[9])+";"+str(row[10])+";"+str(row[11])+";"+str(row[12])
               +";"+str(row[13])+";"+str(row[14])+"\n")

How can I write in the beginning of the file the column names for a variable amount of columns, so that I don't have to hardcode it? Also the hardcoded concatenation is pretty ugly.

Upvotes: 0

Views: 1248

Answers (2)

Anthony Tuininga
Anthony Tuininga

Reputation: 7096

Ebrahim Jackoet has already mentioned that you can use cursor.description to get the column names from your query. If you don't have a very large number of rows to process, though, the csv module is built in and makes writing rows simple. It also handles all of the necessary quoting

An example follows:

import csv

with open("myfile.csv", "w") as outfile:
    writer = csv.writer(outfile, delimiter = ";")
    for row in cursor:
        writer.writerow(row)

Upvotes: 1

Ebrahim Jakoet
Ebrahim Jakoet

Reputation: 417

You could use the description

desc = cursor.description 

function. It returns a sequence of 7 item sequences and you can get the column names from

for seq in desc:
    print seq[0]

I would also recommend using pandas to do your writing to csv.

Upvotes: 2

Related Questions