Python - 将 headers 写入 csv

Python - write headers to csv

目前我正在 python 中编写查询,它将数据从 oracle dbo 导出到 .csv 文件。我不确定如何在文件中写入 headers。

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

您可以在执行查询后执行此操作:

columns = [i[0] for i in cursor.description]

所以你得到

query = """select * from """ .format(line_name)
tmp = cursor.execute(query)
columns = [i[0] for i in cursor.description]
results = tmp.fetchall()

然后做:

if results:
    myFile = csv.writer(csv_file)
    myFile.writerow(columns)
    myFile.writerows(results)

或者您可以将结果转换为字典并使用 DictWriter 接受字段名