Wik*_*ski 4 python csv cx-oracle export-to-csv
目前我在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()
Run Code Online (Sandbox Code Playgroud)
执行查询后,您可以执行此操作:
columns = [i[0] for i in cursor.description]
Run Code Online (Sandbox Code Playgroud)
所以你得到了
query = """select * from """ .format(line_name)
tmp = cursor.execute(query)
columns = [i[0] for i in cursor.description]
results = tmp.fetchall()
Run Code Online (Sandbox Code Playgroud)
然后做:
if results:
myFile = csv.writer(csv_file)
myFile.writerow(columns)
myFile.writerows(results)
Run Code Online (Sandbox Code Playgroud)
或者你可以将结果转换为字典并使用DictWriter女巫接受字段名称