'How to save the results of a for loop into one singular JSON file

I am trying to utilize the twitter api for a class, to iterate through a list of NBA team names, and pull tweets that have each specific name from twitter. I have a for loop that runs through each team name in my list of team names, but I don't know how to save each output into one singular json_file.

Code

I can add a = in next to search_twitter, but it just saves only the results of the last team in the list.



Solution 1:[1]

Do not post pictures of the code, post the actual code in the post.

The reason you only end up with the last team as a is because it's overwritten after each iteration. What you want to do is append that a = part to a list so that after each iteration it's stored somewhere.

Then you can write that to file.

data = []
for x in team_name:
    a = search_twitter(query_x, tweet_fields=tweet_fields, bearer_token=BEARER_TOKEN)
    data.append(a)
    
import json
with open('data.json', 'w') as f:
    json.dump(data, f)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 chitown88