我有很多邮政编码(超过12,000个),需要从API请求并保存响应。
我当前的解决方案是单独请求它们,但python返回
RecursionError: maximum recursion depth exceeded during compilation
超过37,000条线。
我正在寻找一种更简单的方法来请求所有邮政编码并保存响应。
下面是用于一次请求一个邮政编码并保存的代码
邮政编码存储在Excel电子表格中。
# Import Libraries
import urllib.parse
import requests
from datetime import datetime
# Call the API
main_api = 'https://doitonline.york.gov.uk/BinsApi/EXOR/getWasteCollectionsForPostCode?'
postcode = "YO1 6EH"
url = main_api + urllib.parse.urlencode({'postcode': postcode})
json_data = requests.get(url).json()
print(json_data)
now = datetime.now()
saveFile = open("test"+str(now)+".txt", "w")
saveFile.write(str(json_data))
saveFile.close()
谢谢, 本
答案 0 :(得分:0)
哼,您可能永远不会在这里创建尽可能多的变量。如果您的年龄在30-40岁之间,您真的应该有所不同,那么36,000 ...
所以,现在:
"postCodes"
中"test" + str(now) + ".txt"
main_api = 'https://doitonline.york.gov.uk/BinsApi/EXOR/getWasteCollectionsForPostCode?'
now = datetime.now()
with open("postCodes") as postcodes,\
open("test" + str(now) + ".txt", "w") as saveFile:
for postcode in postcodes:
postcode = postcode.rstrip()
url = main_api + urllib.parse.urlencode({'postcode': postcode})
json_data = requests.get(url).json()
saveFile.write(str(json_data) + "\n")