0

When I ran the code, I encountered the following error :

IndexError: list index out of range

What is wrong in my code?

fin = open('words.txt')

for line in fin:
    word = line.strip()
    if len(word) > 20:
        print(word)

print(fin.readlines()[1])  #It is in this line that the error report shows
1
  • 1
    Use a context manager to handle files. That readlines() will produce nothing since you’re at the end of the file. Please see: ericlippert.com/2014/03/05/how-to-debug-small-programs. Can you explain what you’re trying to do with this code? Commented Dec 6, 2019 at 7:01

2 Answers 2

2

You are trying to get second element (starting from zero) of the result of execution readlines method. It's unsafe by default as file can contain only one string. But in this particular case you will receive empty list in fin.readlines() regardless to count of lines in opened file because you've already read lines above (using for line in fin loop). You can't just read it twice and need to seek to the beginning or reopen file:

~  echo 1 >> t.txt
~  echo 2 >> t.txt
~  echo 3 >> t.txt
~  python3

Twice reading contents:

>>> with open('t.txt') as f:
...   f.readlines()
...   f.readlines()
...
['1\n', '2\n', '3\n']
[]

Seeking to begin:

>>> with open('t.txt') as f:
...   f.readlines()
...   f.seek(0)
...   f.readlines()
...
['1\n', '2\n', '3\n']
0
['1\n', '2\n', '3\n']
Sign up to request clarification or add additional context in comments.

Comments

0

This is because file read after the loop has already reached its end. With seek, you can set the pointer again to the beginning.

fin = open('text_file.txt')

for line in fin:
    word = line.strip()
    if len(word) > 20:
        print(word)
fin.seek(0, 0)
print(fin.readlines()[1])

Here is a link to it https://python-reference.readthedocs.io/en/latest/docs/file/seek.html
It is unclear what exactly you want to do still? But the error should disappear.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.