【发布时间】:2017-11-05 06:43:18
【问题描述】:
我正在从 python API 运行 SQL 查询,并希望收集结构化数据(在他们自己的标题下的列数据).CSV 格式。
这是我目前的代码。
import pymysql.cursors
import csv
conn = pymysql.connect(host='159.XXX.XXX.XXX',user='proXXX',password='PXX',db='pXX',charset='utf8mb4',cursorclass=pymysql.cursors.DictCursor)
cursor = conn.cursor()
print (type(conn))
sql = "SELECT id,author From researches WHERE id < 20 "
cursor.execute(sql)
data = cursor.fetchall()
print (data)
with open('metadata.csv', 'w', newline='') as f_handle:
writer = csv.writer(f_handle,delimiter=',')
header = ['id', 'author']
writer.writerow(header)
for row in data:
writer.writerow(row)
现在数据正在控制台上打印,但没有进入 .CSV 文件,这就是我得到的 asnoutput。我错过了什么?请帮忙。
【问题讨论】:
-
你是在循环调用这段代码吗?
-
是的,有没有更好的办法?
-
你应该使用
a模式,否则你每次都重写你的文件。另外,只写一次标题... -
我对此很陌生。你能帮我写代码吗?
-
也许...如果您可以更新您的问题以包括如何调用此代码 - 我想查看循环和任何其他相关代码,以便我可以向您展示如何修复它。
标签: python csv export-to-csv