Python - cx_oracle 打印可变数量的列名

Python - cx_oracle print variable amount of column names

基于给定的 SQL-语句,我使用以下函数从数据库中提取到 CSV:

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")

如何在文件的开头写入可变数量的列的列名,以便我不必对其进行硬编码?硬编码的连接也很丑陋。

您可以使用 description

desc = cursor.description 

函数。它 returns 一个包含 7 个项目序列的序列,您可以从

中获取列名
for seq in desc:
    print seq[0]

我还建议使用 pandas 来写入 csv。

Ebrahim Jackoet 已经提到您可以使用 cursor.description 从查询中获取列名。但是,如果您没有大量的行要处理,csv module 是内置的,可以使写入行变得简单。它还处理所有必要的引用

示例如下:

import csv

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