首页 > 解决方案 > 将每个请求的json响应写入文件

问题描述

我编写了一个向 API 发出请求并以 JSON 格式接收输出的代码。所以我的问题是如何为文件中的每个请求编写输出。现在我的代码正在执行最后一个请求。

import requests
import json

with open("query4.txt", "rt") as file:
        data_file = file.read()

for line in data_file.split("\n"):
        drX, drY, fromX, fromY, dist = line.split(",")

        url = "https://api.openrouteservice.org/directions?"
        params = [
                ["api_key", "my_api_key"],
                ["coordinates", "%s,%s|%s,%s" % (drY, drX, fromY, fromX)],
                ["profile", "driving-car"]
        ]
        headers = {
                "Accept": "application/json, application/geo+json,"
                          "application/gpx+xml, img/png; charset=utf-8"}
        responce = requests.get(url=url, params=params, headers=headers)
        # print(responce.url)
        # print(responce.text)
        result = json.loads(responce.text)
        # print(result)
with open("result.txt", "w+") as f_o:
        for rows in result["routes"]:
                f_o.writelines(json.dumps(rows["summary"]["distance"]))  # depending on how do you want the result
                print(result["routes"])

我有这样的输出:

{'routes': [{'warnings': [{'code': 1, 'message': 'There may be restrictions on some roads'}], 'summary': {'distance': 899.6, 'duration': 102.1}, 'geometry_format': 'encodedpolyline', 'geometry': 'u~uiHir{iFb@SXzADTlAk@JOJ]@_@CWW{AKo@k@eDEYKo@y@{EGc@G]GYCOa@gCc@iCoBsLNGlAm@VK^Sh@Un@tD', 'segments': [{'distance': 899.6, 'duration': 102.1, 'steps': [{'distance': 22.1, 'duration': 5.3, 'type': 11, 'instruction': 'Head south', 'name': '', 'way_points': [0, 1]}, {'distance': 45.4, 'duration': 10.9, 'type': 1, 'instruction': 'Turn right', 'name': '', 'way_points': [1, 3]}, {'distance': 645.5, 'duration': 52.3, 'type': 0, 'instruction': 'Turn left onto Партизанська вулиця', 'name': 'Партизанська вулиця', 'way_points': [3, 21]}, {'distance': 114.4, 'duration': 20.6, 'type': 1, 'instruction': 'Turn right', 'name': '', 'way_points': [21, 26]}, {'distance': 72.1, 'duration': 13, 'type': 1, 'instruction': 'Turn right', 'name': '', 'way_points': [26, 27]}, {'distance': 0, 'duration': 0, 'type': 10, 'instruction': 'Arrive at your destination, on the left', 'name': '', 'way_points': [27, 27]}]}], 'way_points': [0, 27], 'extras': {'roadaccessrestrictions': {'values': [[0, 1, 0], [1, 3, 2], [3, 27, 0]], 'summary': [{'value': 0, 'distance': 854.2, 'amount': 94.95}, {'value': 2, 'distance': 45.4, 'amount': 5.05}]}}, 'bbox': [38.484536, 48.941171, 38.492904, 48.943022]}], 'bbox': [38.484536, 48.941171, 38.492904, 48.943022], 'info': {'attribution': 'openrouteservice.org | OpenStreetMap contributors', 'engine': {'version': '5.0.1', 'build_date': '2019-05-29T14:22:56Z'}, 'service': 'routing', 'timestamp': 1568280549854, 'query': {'profile': 'driving-car', 'preference': 'fastest', 'coordinates': [[38.485115, 48.942059], [38.492073, 48.941676]], 'language': 'en', 'units': 'm', 'geometry': True, 'geometry_format': 'encodedpolyline', 'instructions_format': 'text', 'instructions': True, 'elevation': False}}}
{'routes': [{'summary': {'distance': 2298, 'duration': 365.6}, 'geometry_format': 'encodedpolyline', 'geometry': 'u~a{Gee`zDLIvBvDpClCtA|AXHXCp@m@bBsBvBmC`AmAtIoKNVLXHPb@c@`A_AFENGzAc@XKZCJ?PDLBH@F?T?PC~CcATOt@Sd@QLKBCBAb@]ZG|@OY_DQ}IE{DC_DAg@Eg@q@aFgBuH^GjBFj@

我做了 NeverHopeless 的回答,但我也有同样的答案:

        result = json.loads(responce.text)
        i = 0
with open(f"result-{i}.txt", "w+") as f_o:
        i += 1
        for rows in result["routes"]:
                f_o.writelines(json.dumps(rows["summary"]["distance"]))  # depending on how do you want the result
                print(result["routes"])

输出现在看起来像这样 899.622982138.832633191.8 我期望得到这个:

2298
2138.8
3263
3191.8

每个值都是与不同请求的距离,因此我需要将每个值都放在新行上。

标签: pythonjson

解决方案


您需要在循环之前打开并保持打开输出文件:

import requests
import json

with open("query4.txt", "rt") as file:
        data_file = file.read()

with open("result.txt", "w") as f_o:
    for line in data_file.split("\n"):
            drX, drY, fromX, fromY, dist = line.split(",")

            url = "https://api.openrouteservice.org/directions?"
            params = [
                    ["api_key", "my_api_key"],
                    ["coordinates", "%s,%s|%s,%s" % (drY, drX, fromY, fromX)],
                    ["profile", "driving-car"]
            ]
            headers = {
                    "Accept": "application/json, application/geo+json,"
                              "application/gpx+xml, img/png; charset=utf-8"}
            responce = requests.get(url=url, params=params, headers=headers)
            # print(responce.url)
            # print(responce.text)
            result = json.loads(responce.text)
            # print(result)
            for rows in result["routes"]:
                    print(rows["summary"]["distance"], file=f_o)  # depending on how do you want the result
                    # print(result["routes"])

推荐阅读