【发布时间】:2021-04-02 19:33:16
【问题描述】:
文末有算法。它从文件 SP500.txt 中读取行。文件包含字符串,它看起来像:
AAA
BBB
CCC
在 get 请求中替换这些字符串并将整个 url 保存到文件 url_requests.txt 中。例如:
https://apidate.com/api/api/AAA.US?api_token=XXXXXXXX&period=d
https://apidate.com/api/api/BBB.US?api_token=XXXXXXXX&period=d
https://apidate.com/api/api/CCC.US?api_token=XXXXXXXX&period=d
然后通过 API 处理每个请求,并将所有响应添加到 responses.txt 中以获取请求。 我不知道如何将来自文件 url_requests.txt 的每个请求的响应保存到单独的 csv 文件而不是 responses.txt 中(现在它们都写入了这个文件,而不是单独)。在这种情况下,使用文件 SP500.txt 中的相应行命名每个文件很重要。例如:
AAA.csv `(which contains data from the request response https://apidate.com/api/api/AAA.US?api_token=XXXXXXXX&period=d)`
BBB.csv `(which contains data from the request response https://apidate.com/api/api/BBB.US?api_token=XXXXXXXX&period=d)`
CCC.csv `(which contains data from the request response https://apidate.com/api/api/CCC.US?api_token=XXXXXXXX&period=d)`
所以,算法是:
import requests
# to use strip to remove spaces in textfiles.
import sys
# two variables to squeeze a string between these two so it will become a full uri
part1 = 'https://apidate.com/api/api/'
part2 = '.US?api_token=XXXXXXXX&period=d'
# open the outputfile before the for loop
text_file = open("url_requests.txt", "w")
# open the file which contains the strings
with open('SP500.txt', 'r') as f:
for i in f:
uri = part1 + i.strip(' \n\t') + part2
print(uri)
text_file.write(uri)
text_file.write("\n")
text_file.close()
# open a new file textfile for saving the responses from the api
text_file = open("responses.txt", "w")
# send every uri to the api and write the respones to a textfile
with open('url_requests.txt', 'r') as f2:
for i in f2:
uri = i.strip(' \n\t')
batch = requests.get(i)
data = batch.text
print(data)
text_file.write(data)
text_file.write('\n')
text_file.close()
而且我知道如何从这个响应中保存 csv。就像:
import csv
import requests
url = "https://apidate.com/api/api/AAA.US?api_token=XXXXXXXX&period=d"
response = requests.get(url)
with open('out.csv', 'w') as f:
writer = csv.writer(f)
for line in response.iter_lines():
writer.writerow(line.decode('utf-8').split(','))
【问题讨论】:
-
您显示的代码到底有什么问题?
-
还有什么问题?你收到错误信息吗?始终将完整的错误消息(以单词“Traceback”开头)作为文本(不是屏幕截图)提出问题(不是评论)。还有其他有用的信息。
-
从
SP500.txt读取数据可能会更好,并作为列表或字典一直保存在内存中。然后您可以创建对线["AAA", 'https://...AAA...']并使用它来获取https://...AAA...的数据并保存在AAA.csv或将"AAA", 'https://...AAA...'保留在'url_requests.txt'中 -
顺便说一句;如果您使用
strip()不带参数,那么它将使用' \n\t' -
要保存在不同的文件中,您必须在
for-loop 中使用open(f"{name}.csv", "w")。
标签: python api csv writetofile get-request