【问题标题】:Python - write headers to csvPython - 将标头写入 csv
【发布时间】:2015-12-08 19:21:00
【问题描述】:

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

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

【问题讨论】:

    标签: python csv export-to-csv cx-oracle


    【解决方案1】:

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

    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 女巫接受字段名

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-10-17
      • 2018-05-15
      • 1970-01-01
      • 2017-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多