How do I print a .txt file line-by-line?

Question:

I am making my first game and want to create a score board within a .txt file, however when I try and print the score board it doesn’t work.

with open("Scores.txt", "r") as scores:
        for i in range(len(score.readlines())):
          print(score.readlines(i + 1))

Instead of printing each line of the .txt file as I expected it to instead it just prints []

The contents of the .txt file are:

NAME: AGE: GENDER: SCORE:

I know it’s only one line but it should still work shouldn’t it?

*Note there are spaces between each word in the .txt file, though Stack Overflow formatting doesn’t allow me to show that.

Asked By: MrDDog

||

Answers:

.readlines() reads everything until it reaches the end of the file. Calling it repeatedly will return [] as the file seeker is already at the end.

Try iterating over the file like so:

with open("Scores.txt", "r") as scores:
    for line in scores:
        print(line.rstrip())
Answered By: Bharel

Assign the result of score.readlines() to a variable. Then you can loop through it and index it.

with open("Scores.txt", "r") as scores:
    scorelines = scores.readlines()

for line in scorelines:
    print(line)
Answered By: Barmar
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.