2017-11-04 241 views
0

我正在從python API運行SQL查詢,並且想要收集Structured(列標題下的數據)標題下的數據.CSV格式。SQL查詢輸出到.csv

這是迄今爲止我的代碼。

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) 
    header = ['id', 'author'] 
    writer.writerow(header) 
    for row in data: 
     writer.writerow(row) 

現在正在打印控制檯上的數據,但在.CSV沒有得到文件這是我得到的output

什麼,我很想念?

+1

您有什麼問題? Python有'csv.writer'來將CSV寫入文件,因此您只需將SQL結果讀取到列表中即可。 – Barmar

+0

你到目前爲止嘗試過什麼? –

+0

問題是我不知道該怎麼做。你能幫我看看基於這個查詢的示例代碼嗎? – Hayat

回答

0

這裏是你正在嘗試做一個簡單的例子:

import sqlite3 as db 
import csv 

# Run your query, the result is stored as `data` 
with db.connect('vehicles.db') as conn: 
    cur = conn.cursor() 
    sql = "SELECT make, style, color, plate FROM vehicle_vehicle" 
    cur.execute(sql) 
    data = cur.fetchall() 

# Create the csv file 
with open('vehicle.csv', 'w', newline='') as f_handle: 
    writer = csv.writer(f_handle) 
    # Add the header/column names 
    header = ['make', 'style', 'color', 'plate'] 
    writer.writerow(header) 
    # Iterate over `data` and write to the csv file 
    for row in data: 
     writer.writerow(row) 
+0

謝謝,@diek。只有一個問題,在獲得數據內的所有內容之後。我們打開爲'vehicle.csv',這個文件來自哪裏以及它正在播放什麼部分?我的意思是我們沒有將數據寫入'vehicle.csv'所以..? – Hayat

+0

@Hayat Python將創建該文件。它正在播放的角色是您的問題的答案,您想創建一個csv文件。 – diek

+0

@Hayat我在代碼中添加了評論,希望這會幫助你理解。閱讀本文將幫助您更好地理解 https://docs.python.org/3/tutorial/inputoutput.html – diek