0

I'm new to Python and so am confused by the following "list index out of range" error I get with the following code as my text file only contains 4 items in it which are first name, last name, hourly salary, total hours worked. Should this be changed to something that's not a while loop? If need be I can give the entire code. Any help would be greatly appreciated!

while line2 != "":
    line2 = " "
    line2 = line2.split( " " )
    if (line2[ 0 ]+ " " + line2[ 1 ]) != name1.rstrip( " \n " ):
    empFile3.write(line2[ 0 ] + " " + line2[ 1 ] + " " + line2[ 2 ] + " " + line2[ 3 ] + " \n " )

1 Answer 1

1

The problem is in line no. 2. Remove that. You are getting that error because you are trying to split an empty string.

while line2 != "":
    line2 = line2.split( " " )
    if (line2[ 0 ]+ " " + line2[ 1 ]) != name1.rstrip( " \n " ):
       empFile3.write(line2[ 0 ] + " " + line2[ 1 ] + " " + line2[ 2 ] + " " + line2[ 3 ] + " \n " )
Sign up to request clarification or add additional context in comments.

4 Comments

Hi and thank you. I removed line no. 2 and am still getting the error. Should I be using a "for" loop instead? Sorry in advance for the newbie question.
Sorry, am getting the following error, "'list' object has no attribute 'split".
You cannot split a list object. Split can only be used on a string. If you have a list of string them loop over the list and use split. For example: [x.split(" ") for x in list]
Thank you, Ashok. I'm new to Python and am trying to make sense of it all. Thank you for your example, that helps out a lot.

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.