1

Here is info from the .txt file I am trying to access:
Movies: Drama
Possession, 2002
The Big Chill, 1983
Crimson Tide, 1995

Here is my code:

fp = open("Movies.txt", "r")  
lines = fp.readlines()
for line in lines:  
    values = line.split(", ")   
    year = int(values[1])
    if year < 1990:  
        print(values[0])   

I get an error message "IndexError: list index out of range". Please explain why or how I can fix this. Thank you!

4
  • 2
    your first line in the file is Movies: Drama There is no , in this. So when you split at lines.split(', ') the resulting list is just one entry that says: ['Movies: Drama']. So values[1]` will be list index out of range Commented Dec 16, 2021 at 1:03
  • The first line of your file does not contain a comma, therefore the .split() returned a list with only one element, there values[1] does not exist when processing that line. One solution would be to do header = fp.readline() just after opening the file, so that the main for loop never sees that line. Commented Dec 16, 2021 at 1:04
  • When I changed the .txt file and got rid of what you said, it worked. THANK YOU Commented Dec 16, 2021 at 1:10
  • Welcome to Stack Overflow. Please read ericlippert.com/2014/03/05/how-to-debug-small-programs. Your first instinct when you get an error message should be to read it, and try to understand it. The error message will tell you which line of code caused the problem (here, trying to do values[1] failed), and why ([1] is the index; it is "out of range"; therefore, values doesn't have enough elements in it for there to be a [1] to access). From there, you work backwards (values was determined by line.split(", ") - so, what did that do?) Commented Dec 16, 2021 at 3:02

3 Answers 3

1

Assuming your .txt file includes the "Movies: Drama" line, as you listed, it's because the first line of the text file has no comma in it. Therefore splitting that first line on a comma only results in 1 element (element 0), NOT 2, and therefore there is no values[1] for the first line.

It's not unusual for data files to have a header line that doesn't contain actual data. Import modules like Pandas will typically handle this automatically, but open() and readlines() don't differentiate.

The easiest thing to do is just slice your list variable (lines) so you don't include the first line in your loop:

fp = open("Movies.txt", "r")
lines = fp.readlines()
for line in lines[1:]:  
    values = line.split(", ")   
    year = int(values[1])
    if year < 1990:  
        print(values[0])

Note the "lines[1:]" modification. This way you only loop starting from the second line (the first line is lines[0]) and go to the end.

Sign up to request clarification or add additional context in comments.

Comments

0

The first line of the text file does not have a ", ", so when you split on it, you get a list of size 1. When you access the 2nd element with values[1] then you are accessing outside the length of the array, hence the IndexError. You need to do a check on the line before making the assumption about the size of the list. Some options:

  1. Check the length of values and continue if it's too short.
  2. Check that ', ' is in the line before splitting on it.
  3. Use a regex which will ensure the ', ' is there as well as can ensure that the contents after the comma represent a number.
  4. Preemptively strip off the first line in lines if you know that it's the header.

Comments

0

Your first line of your txt file has wrong index Just simple change your code to:

fp = open("Movies.txt", "r")  
lines = fp.readlines()
for line in lines:  
    try: #<---- Here
        values = line.split(", ")   
        year = int(values[1])
        if year < 1990:  
            print(values[0])
    except: #<--------And here
        pass

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

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.