Home > Mobile >  Looping through values in an API and saving to a txt file
Looping through values in an API and saving to a txt file

Time:06-18

I am using a Pokemon API : https://pokeapi.co/api/v2/pokemon/ and I am trying to make a list which can store 6 pokemon ID's then, using a for loop, call to the API and retrieve data for each pokemon. Finally, I want to save this info in a txt file. This is what I have so far:

import random
import requests
from pprint import pprint


pokemon_number = []
for i in range (0,6):
    pokemon_number.append(random.randint(1,10))

url = 'https://pokeapi.co/api/v2/pokemon/{}/'.format(pokemon_number)

response = requests.get(url)
pokemon = response.json()
pprint(pokemon)

with open('pokemon.txt', 'w') as pok:
    pok.write(pokemon_number)

I don't understand how to get the API to read the IDs from the list.

I hope this is clear, I am in a right pickle.

Thanks

CodePudding user response:

You are passing pokemon_number to the url variable, which is a list. You need to iterate over the list instead.

Also, to actually save the pokemon, you can use either the name or it's ID as the filename. The JSON library allows for easy saving of objects to JSON files.

import random
import requests
import json


# renamed this one to indicate it's not a single number
pokemon_numbers = []
for i in range (0,6):
    pokemon_numbers.append(random.randint(1,10))


# looping over the generated IDs
for id in pokemon_numbers:
    url = f"https://pokeapi.co/api/v2/pokemon/{id}/"
    # if you use response, you overshadow response from the requests library
    resp = requests.get(url)
    pokemon = resp.json()
    print(pokemon['name'])
    with open(f"{pokemon['name']}.json", "w") as outfile:
        json.dump(pokemon, outfile, indent=4)

CodePudding user response:

I now have this:

import requests

pokemon_number = []
for i in range (0,6):
    pokemon_number.append(random.randint(1,50))

x = 0
while x <len(pokemon_number):
    print(pokemon_number[x])
    x = x  1

url = 'https://pokeapi.co/api/v2/pokemon/{}/'.format(pokemon_number[])

response = requests.get(url)
pokemon = response.json()
print(pokemon)
print(pokemon['name'])
print(pokemon['height'])
print(pokemon['weight'])

with open('pokemon.txt', 'w') as p:
    p.write(pokemon['name'])
    p.write(pokemon['ability'])
  • Related