Search code examples
pythonpython-3.7

How to use an array within a .txt document to create an object


I have a text file with 10 arrays, 1 on each line. The code is supposed to take one of these arrays, and use each element to create an object from a class.

Here is the code:

class character(metaclass=ABCMeta):

    def __init__(self, name, lvl, hp,):
        self._name =  name
        self._lvl =  lvl
        self._hp = hp
        
    def stats(self):
        print("Name:", self._name)
        print("Level:", self._lvl)
        print("HP:", self._hp)

def venture():
    with open("Zone1.txt") as text:
        entries = text.readlines()
        search =(random.choice((entries))
        monster = character(search[0], search[1], search[2])

With the arrays in "Zone1.txt" looking like this:

["Fish", 5, 14]

Instead of pulling element 1, 2 & 3, it pulls the 1st, 2nd and 3rd character in the line.

Any help is appreciated and I will try to answer any question presented to me. I also wasn't sure how to properly describe my problem, and therefore couldn't find an existing question so apologies if dupe.


Solution

  • since you're reading from a text file, each line of the file is a string and not a list. you can convert this string into a list using a package called json:

    import json
    
    
    search =json.loads(random.choice(entries))