【问题标题】:Python - cx_oracle print variable amount of column namesPython - cx_oracle 打印可变数量的列名
【发布时间】:2016-10-19 06:28:58
【问题描述】:

基于给定的 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")

我怎样才能在文件的开头为可变数量的列写列名,这样我就不必硬编码了?硬编码的连接也很丑陋。

【问题讨论】:

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


    【解决方案1】:

    您可以使用description

    desc = cursor.description 
    

    功能。它返回一个由 7 个项目序列组成的序列,您可以从中获取列名

    for seq in desc:
        print seq[0]
    

    我还建议您使用 pandas 对 csv 进行写入。

    【讨论】:

      【解决方案2】:

      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)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-02-28
        • 1970-01-01
        • 2016-06-07
        • 1970-01-01
        • 2018-12-23
        • 1970-01-01
        相关资源
        最近更新 更多