Semyon Kolesnikov
Semyon Kolesnikov

Reputation: 55

Write json responce for each request into a file

I wrote a code which is making a request to API and recieving output in JSON. So my question is how to write output for each request in file. Now my code is doing the last one request.

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"])

I have an output like this:

{'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@

I did NeverHopeless answer, but i've got the same:

        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"])

Output now looks like this 899.622982138.832633191.8 I'm expecting to get this:

2298
2138.8
3263
3191.8

Every value is a distance from different requests so i need to have each on the new line.

Upvotes: 1

Views: 147

Answers (3)

Booboo
Booboo

Reputation: 44108

You need to open and keep open the output file before your loop:

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"])

Upvotes: 2

0xM4x
0xM4x

Reputation: 470

I think it's better to write results in different files with timestamp. in this way you don't rewrite on your older file and also you can find them easier.

current_time = time.strftime("%m_%d_%y %H_%M_%S", time.localtime())

with open(current_time + ".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"])

Upvotes: 2

NeverHopeless
NeverHopeless

Reputation: 11233

You need to make this filename "result.txt" dynamic. Currently it is overwriting content.

Perhaps like this:

i = 0   # <----- Keep it outside your for loop or it will be always set to zero
with open(f"result-{i}.txt", "w+") as f_o:
    i += 1

Or instead of integers, you may better use timestamp in filename.

Upvotes: 1

Related Questions