[英]how do you write output of sql to a csv file in python
我正在嘗試連接到oracle表並執行sql。 我需要將結果集導出到csv文件。 我的代碼如下:
import pyodbc
import csv
cnxn = pyodbc.connect("DSN=11g;UID=test101;PWD=passwd")
cursor = cnxn.cursor()
cursor.execute(sql)
row = cursor.fetchall()
with open('data.csv', 'w', newline='') as fp:
a = csv.writer(fp, delimiter=',')
for line in row:
a.writerows(line)
cursor.close()
當我在for循環中打印到行時,我得到這樣的東西:
('Production', 'farm1', 'dc1prb01', 'web')
('Production', 'farv2', 'dc2pr2db01', 'app.3')
('Production', 'farm5', 'dc2pr2db02', 'db.3')
這不起作用。 任何想法我可能會失蹤?
這將是一行的寫作:
a.writerow(line)
writerows
期望迭代的迭代次數,因此它會迭代遍歷每個char的子串。
如果你想使用writer在行上調用它:
row = cursor.fetchall()
with open('data.csv', 'w', newline='') as fp:
a = csv.writer(fp, delimiter=',')
a.writerows(row)
如果您使用的是python2,則刪除newline=''
,換行符是* python * 3關鍵字:
row = cursor.fetchall()
with open('data.csv', 'w') as fp:
a = csv.writer(fp, delimiter=',')
a.writerows(row)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.