pythonjsonapipython-requestsrewriting

MCC API Players Names into Text Files


I'm currently playing with the MCC API and I want to put every players name in their own text file within their team folder. This is the code that I have currently:

import requests
r = requests.get("https://api.mcchampionship.com/v1/participants")

# TEAMS

# RED
# Player 1
DATA_Red_p1 = open("./Players/Red/player1.txt", "w")
DATA_Red_p1.write(str(r.json()['data']['RED'][0]['username']))
DATA_Red_p1.close()
# Player 2
DATA_Red_p2 = open("./Players/Red/player2.txt", "w")
DATA_Red_p2.write(str(r.json()['data']['RED'][1]['username']))
DATA_Red_p2.close()
# Player 3
# ...
# Player 4
# ...

I have the same code copy and pasted (excluding the import and the api fetch) for each team, just with different variables and file paths. The teams are: Red, orange, yellow, lime, green, cyan, aqua, blue, purple and pink. I was just wondering if there was an easier way of writing the code.


Solution

  • Yes you can do that using a for-loop. However this will output 10 text files, is that desired? Or do you prefer to store all in 1 text file?

    import requests
    #import os
    
    r = requests.get("https://api.mcchampionship.com/v1/participants")
    response = r.json()
    file_path = './Players/Red'
    #file_path = os.getcwd()
    for i, color in enumerate(response['data'].keys()):
        if color != 'SPECTATORS' and color != 'NONE':
            f = open(file_path + '/player' + str(i+1) + '.txt', 'w')
            f.write(str(response['data'][color][0]['username']))
            f.close()
    

    Output:

    player1.txt
    player2.txt
    player3.txt
    player4.txt
    player5.txt
    player6.txt
    player7.txt
    player8.txt
    player9.txt
    player10.txt
    

    If you would like to save the list into 1 file, you could do this:

    f = open(file_path + '/players.txt', 'a')
    for color in response['data'].keys():
        if color != 'SPECTATORS' and color != 'NONE':
            f.write(str(response['data'][color][0]['username']) + '\n')
    f.close()