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


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:


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



.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:
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:
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.