Search code examples
pythonlistloopsfile-handlingnamedtuple

How to loop until all lines read from a file?


I'm trying to set up a score system where I need to input all the scores from a text file into an 'array of records'.

I'm fairly new to Python and hope for a simple solution.

In my program, the array of records would technically class as a list of namedtuples.

Currently I have:

Player = namedtuple("Player", ["name", "result", "difficulty", "score"])

Playerlist = []
while str(f.readline) != '':
    player = Player(
        f.readline(),
        f.readline(),
        f.readline(),
        f.readline())
    Playerlist.append(player)

I tried to print(Playerlist[0]), but nothing shows up.

I have also tried to print(Playerlist[0]) without any loop and got the expected result, though I won't have stored all the data from the text file into my program.

An example of what is in the text file (scores.txt):

George
lost
H
18
Holly
lost
H
28
Marcus
won
H
30

EDIT: I tried:

with open("scores.txt", "r") as f:
    for line in f:
        player = Player(
            f.readline(),
            f.readline(),
            f.readline(),
            f.readline())
        Playerlist.append(player)

However all of the contents came out mixed up:

Player(name='H\n', result='28\n', difficulty='Marcus\n', score='won\n')

Solution

  • Since you are using while str(f.readline) != '': it reads first line. Therefore, first line(and by extension all lines between records) must have blank line. Also readline in your while is missing paranthesis(). Other than that the code is working in python 3. You can use with to open file:

    with open('test.txt', 'r') as f:
        while True:
            player = Player(f.readline(), f.readline(), f.readline(), f.readline())
            if "" in player:
                break;
            Playerlist.append(player)
    
    for i in range(len(Playerlist)):
        print (Playerlist[i])
    

    It automatically closes files and handles details for you. However, using json or other formats in a better option.