Python API에서 SQL 쿼리를 실행하고 구조화 된 데이터 (자체 헤더의 열 데이터) .CSV 형식을 수집하려고합니다.Python API에서 csv에 sql 데이터 작성
이것은 지금까지 가지고있는 코드입니다.
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)
이제 데이터는 콘솔에 인쇄하지만 in.CSV이 내가
output ASN 얻고 무엇을 파일 못하고되고있다. 내가 누락 된 것은 무엇인가? 도와주세요.
루프에서이 코드를 호출하고 있습니까? –
예, 더 좋은 방법이 있습니까? – Shad
'a' 모드를 사용해야합니다. 그렇지 않으면 매번 파일을 다시 씁니다. 또한 한 번만 헤더를 작성하십시오 ... –