-1

so i created a class that holds a baseball players year, name, stats. I am now trying to read from a txt file that holds the players information and create a list of objects. I cannot seem to figure out how to do so.

Here is the class:

class PlayersYear:
    def __init__(self, year, player, stats):

        self.__year = int(year)
        self.__player = player
        self.__stats = stats

Now I am trying to read from a file that list the stats like this lets call it baseball.txt:

1971Hank Aaron:162:22:3:47:495
2002Barry Bonds:149:31:2:46:403
1974Rod Carew:218:30:5:3:599

i am trying to read these in an create an PlayersYear object and append it to a list. I am completely lost and would appreciate some help. Thank you!

This is what I have and I know its wrong

def readPlayerFile(filename):
    baseball = []
    file_in = open(filename, 'r')

    lines = file_in.readlines()

    for i in lines:
        baseball.append(PlayersYear(year, name, stats))

    file_in.close()

    return baseball
Andrew
  • 9
  • 1
  • 2
  • 1
    Possible duplicate of [How do I read a file line-by-line into a list?](https://stackoverflow.com/questions/3277503/how-do-i-read-a-file-line-by-line-into-a-list) – Derek Brown Nov 07 '17 at 01:24
  • I know how to read from a text file but I dont know how to create an a PlayersYear object from the text in the file. – Andrew Nov 07 '17 at 01:38
  • https://stackoverflow.com/questions/15081542/python-creating-objects – Derek Brown Nov 07 '17 at 01:39
  • SO has a lot of resources already- you should do research on your own before asking. – Derek Brown Nov 07 '17 at 01:39
  • Derek I have been researching. I dont know how to separate the date, name, and the stats into year, name, stats. So that i can pass it to PlayersYear – Andrew Nov 07 '17 at 02:17

1 Answers1

0

Is this will help you? It just separate the player name, year and status

def playerList(fileName):
    file = open(fileName, 'r')
    nameList = []
    for line in file:
        line = line[4:]
        name = line.split(":")[0]
        nameList.append(name)
    return nameList


def statusList(fileName,satusLocation):
    file = open(fileName, 'r')
    statusList = []
    for line in file:
        status = line.split(":")[satusLocation]
    statusList.append(status)
    return statusList

def yearList(fileName):
    file = open(fileName, 'r')
    years = []
    for line in file:
        line = line[:4]
        years.append(line)
    return years
patjing
  • 21
  • 8