我正在从python API运行SQL查询,并希望收集Structured中的数据(在他们自己的标题下的列式数据).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文件这就是我得到的output。我错过了什么?请帮忙。
答案 0 :(得分:2)
with open('metadata.csv', 'w', newline='') as f_handle:
fieldnames = ['id', 'author']
writer = csv.DictWriter(f_handle, fieldnames=fieldnames)
writer.writeheader()
for row in data:
writer.writerow(row)
所以问题是,你的数据采用字典的形式,而Writer对象则需要元组。您应该使用DictWriter对象。