lines = [11,22,50]
f=open('erste_seite_test2.txt')
line_number = 0
for i in lines:
f.readlines()[i]
why does this throw an IndexError: list index out of range when the text file has more than 50 lines and how can I fix my code?
CodePudding user response:
The problem really is that you are calling readlines
within the loop, which will give you an empty list starting from the second iteration. Think that the end of the file is reached the first time you call readlines
, so you'd have to reset it to use it again, but better just store it in a variable and it will work.
line_numbers = [11,22,50]
f=open('erste_seite_test2.txt')
lines = f.readlines()
for i in line_numbers:
print(lines[i])
CodePudding user response:
I don't fully understand your issue. However, based on my understanding, this is the simplest code that will work if your text has at least 50 lines:
f = open("erste_seite_test2.txt", "r")
lines = f.readlines()
print (lines[50])
It can easily also be re-written with a for loop like in your example, but I don't know why you need a loop.
CodePudding user response:
You can improve you code a couple of ways.
with open
, ensures your file handle gets closed- flip your
for
loop to go over the file not the line numbers of interest (will prevent theIndexError
) for line in <file handle>
iterates through file without loading it all in memory (whichreadlines
does)
line_numbers = [11,22,50]
lines = []
with open("erste_seite_test2.txt", "rt") as f:
for i, line in enumerate(f):
if i in line_numbers:
lines.append(line)
Optionally, move the line_numbers
to a set
to make the if i in line_numbers
more efficient.
CodePudding user response:
I am assuming you're trying to access lines of the file pertaining to the numbers in your list - line 11, line 22, and line 50.
If this is so, you may want to try using the 'linecache' module.
First, of course:
import linecache
Then try:
with open('erste_seite_test2.txt', 'r') as f:
lines = [11, 22, 50]
for value, item in enumerate(lines):
specific_line = linecache.getline('erste_seite_test2.txt', item)
The 'specific_line' variable now contains the specific text from the text file you pulled using the 'lines' list, i.e., it will contain the text from line 11, then line 22, then line 50 after each iteration.
'with open' has been added simply to ensure that the file is closed after.