简体   繁体   中英

How to read a line from a text file and print it

I am trying to write a code which will take each line from a text file and check it against another variable but I can only get the first line to work. After that I get an index error.

file = open ("High_Scores.txt", "r")
for i in range(5):
  lines = file.readlines()
  x = lines[i]
  print(x)

That is my code for fetching the line. I'm sure this is an easy fix but any help would be appreciated. Thanks in advance.

The problem with your code is that file.readlines() reads all the lines, and once they are read, they can not be read again, so in any subsequent iterations of the loop, lines will be empty.

Instead, you can read the lines once, outside of the loop...

lines = file.readlines()
for i in range(5):
    print(lines[i])

... or read a single line within the loop ...

for i in range(5):
    print(file.readline())

... but you can also just iterate the lines in the file directly:

for line in file:
    print(line)

(The first two variants assume that there are at least 5 lines and print those, whereas the last variant will print all lines, no matter how few or many there are.)

Try this to read line by line :

# Using readlines() 
file1 = open('myfile.txt', 'r') 
Lines = file1.readlines() 
  
count = 0
# Strips the newline character 
for line in Lines: 
    print("Line{}: {}".format(count, line.strip())) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM