0

I am making a program that fetches column names and dumps the data into csv format. Now everything is working just fine and data is being dumped into csv, the problem is, I am not able to fetch headers into csv. If I open the exported csv file into excel, only data shows up not the column headers. How do I do that?

Here's my code:

import cx_Oracle
import csv

dsn_tns = cx_Oracle.makedsn(--Details--)
conn = cx_Oracle.connect(--Details--)

d = conn.cursor()

csv_file = open("profile.csv", "w")
writer = csv.writer(csv_file, delimiter=',', lineterminator="\n", quoting=csv.QUOTE_NONNUMERIC)
d.execute("""
select * from all_tab_columns where OWNER = 'ABBAS'
""")
tables_tu = d.fetchall()
for row in tables_tu:
    writer.writerow(row)

conn.close()
csv_file.close()

What code do I use to export headers too in csv?

Muhammad Abbas
  • 47
  • 1
  • 10

1 Answers1

0

Place this just above your for loop:

writer.writerow(i[0] for i in d.description)

Because d.description is a read-only attribute containing 7-tuples that look like:

(name, 
type_code, 
display_size,
internal_size, 
precision, 
scale, 
null_ok)
mechanical_meat
  • 163,903
  • 24
  • 228
  • 223