簡體   English   中英

如何在Python中使用API​​從CSV文件讀取數據

[英]How to read data from a csv file using API in Python

我正在嘗試從以下鏈接下載數據:
NHTSA網站

如果我按以下方式創建鏈接,則它將CSV文件下載到我的計算機上http://webapi.nhtsa.gov/api/SafetyRatings/modelyear/2019/make/ACURA/model/RDX?format=csv

如何使用Python中的API讀取不同車輛的此文件?

到目前為止,這是我的代碼:

db = sql.connect("localhost","root","password","TEST")

cursor = db.cursor()

sql = "SELECT * FROM TEST.car_model"
cursor.execute(sql)

data = cursor.fetchall()

for row in data:
    apiUrl = "http://webapi.nhtsa.gov/api/SafetyRatings/modelyear/"
    apiParams = str(row[1])+"/make/"+row[2].replace(" ","%20")+"/model/"+row[3].rstrip().replace(" ","%20")
    apiFormat = "?format=csv"
    link = apiUrl + apiParams + apiFormat
    response = urlopen(apiUrl + apiParams + apiFormat)

    f = open(link, 'rb')
    reader = csv.reader(f)
    for row in reader:
        print(row)

db.close()

響應會自動將文件下載到我的“下載”文件夾中嗎?

你可以試試這個

model = input("Enter model name: ")
year = input("year: ")

url = "http://webapi.nhtsa.gov/api/SafetyRatings/modelyear/"+year+"/make/ACURA/model/"+model+"?format=csv"

import urllib.request

with urllib.request.urlopen(url) as response:
    html = response.read()

with open(model+year+".csv", "w") as f:
    f.write(html)


您可以在網址中添加更多變量。 然后,您可以使用pandas軟件包進行閱讀。

import pandas as pd
vechiles = pd.read_csv("vichles.csv")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM