Python – Add data to external files and get JSON data from files

initially, the idea of the article was to write four lines of code, doing the following 2 tasks:

    • uploading data to a given file
    • getting JSON data from file and using it in an application

python-logo-master-v3-TM

However, as soon as I started, I considered that I would probably need a little more lines to generate the data in a better way. Thus, I decided to build two classes – class FootballPlayer and class FootballTeam. The FootballTeam is consisted of players, thus I have added the functions  add_to_team(), change_team_list(), show_team(). They are dealing with the dictionary _teamList, which is generated on initialization of the FootballTeam class. The dictionary _teamList is the one, to be uploaded to a file and later downloaded. All of the progress is printed on almost every step, like this:

printJSON

 

So, pretty much that is all, folks! The code is available in GitHub and below:

import json


class FootballTeam:

    def __init__(self):
        self._teamList = {}

    def add_to_team(self, player):
        self._teamList[player] = [player._salary]

    def change_team_list(self, dict):
        self._teamList = {}
        self._teamList = dict

    def show_team(self):
        return self._teamList


class FootballPlayer:
    def __init__(self, name, age, salary):
        self._name = name
        self._age = age
        self._salary = salary

    def __str__(self):
        return self._name + " " + str(self._age)

    def __repr__(self):
        return str(self)

    def salary(self, player):
        return str(player._salary)

AFC_Lions = FootballTeam()

player1 = FootballPlayer("Ivan", 22, 15000)
player2 = FootballPlayer("Stoyan", 23, 16000)
player3 = FootballPlayer("Damyan", 25, 17000)
player4 = FootballPlayer("Kaloyan", 19, 18000)
print(player1)

AFC_Lions.add_to_team(player1)
AFC_Lions.add_to_team(player2)
AFC_Lions.add_to_team(player3)
AFC_Lions.add_to_team(player4)
print(AFC_Lions.show_team())

with open('exported.txt', 'w') as outfile:
    json.dump(str(AFC_Lions.show_team()), outfile)
print("\nPrinting to file is ready!")

print("Now load:")
ownfile = open("imported.txt", "r")
data = ownfile.read()
print("Raw data from the file:\n", data)
print("Data to json:\n", json.loads(data), "\n")
print("Replacing the new data and showing:")
AFC_Lions.change_team_list(json.loads(data))
print(AFC_Lions.show_team())

Enjoy it! 🙂