本篇繼續上一篇「Pyton:下載資料」。
語法
print(response.data)
將檔案內容用純文字的方式顯示出來,現在要利用CSV套件,將檔案內容轉成Python的資料結構。
資料結構就是儲存資料的地方,例如:變數。
Python的基本資料類型有4種
- 整數:int
- 浮點數:float
- 字串:str
- 布林:bool
4種Python的資料結構
- List:有index;List內可以有List,也可以有Dictionary
- Dictionary:辭典物件,沒有index
- Set:集合的概念,裡面的元素不可以重覆
- Tuple:暫存資料用,通常是儲存function的回傳值
#程式開始
from tkinter import * import urllib3 #外部的packages import certifi #https的連線方式 import csv def main(): w=Tk() w.title("範例一") w.geometry("500x300") #沒有設定寬x高,將依元件調整視窗大小 Button(w,text="下載資料",command=downloadAQI).pack(side=LEFT,ipadx=25,ipady=25,expand=YES) w.mainloop() def downloadAQI(): print("開始下載資料") CSV_URL="https://data.epa.gov.tw/api/v1/aqx_p_432?limit=1000&api_key=9be7b239-557b-4c10-9775-78cadfc555e9&format=csv" http=urllib3.PoolManager(cert_reqs='CERT_REQUIRED',ca_certs=certifi.where()) #建立https連線 #如下載網址為http://....則建立http連線為:http = urllib3.PoolManager() response = http.request('GET', CSV_URL) #使用GET方法儲存 if response.status == 200: print("下載成功") #儲存檔案,建立file實體 file=open("空氣品質指標.csv","wb") file.write(response.data) print("存檔成功") #讀取檔案 with open("空氣品質指標.csv","r",encoding='UTF-8') as file: next(file) #跳下一行,不要標題 #content=file.read() #此時content是純文字 #print(content) #利用csv套件,將content轉成資料結構 rows=csv.reader(file) #一次抓取全部內容 #print(rows) #print(list(rows)) #將rows轉成list for item in rows: print(item[0]+item[2]) file.close() #關閉檔案 else: print("下載失敗") return #中斷,跳出downloadAQI if __name__ == "__main__": main()
#程式結束
最終範例請參考老師的LINK(笑)
全站熱搜