Search code examples
pythonlinereadlines

Getting a "list index is out of range" for a simple list split


I am trying to read lines from a txt document into a list, but I keep getting the message: IndexError: list index out of range. It points to the last line password = usersdoc1.strip() as the problem.

k = open(filename, 'r')

lines = k.readlines()

for line in lines:

    
    usersdoc=line.strip().split('-')

    username = usersdoc[0].strip()

    password = usersdoc[1].strip()

The document I am reading has a username and a password on each line separated by '-' and I am able to print username and password successfully, but when I run my full code I just get an error. I can't seem to figure out what the issue is. Here is the document I am reading


Solution

  • When your for loop reaches the line:

    Jack
    

    the function split('-') only returns a list with a single value: "Jack" Said list doesn't have an index of [1] because it only has one value, which is index [0].

    To bypass this, you can do a couple things depending on how you want to handle it:

    Ignore the line entirely:

    for line in lines:
        usersdoc=line.strip().split('-')
        if len(usersdoc) !== 2:
            continue
        username = usersdoc[0].strip()
        password = usersdoc[1].strip()
    

    Create an empty password:

    for line in lines:
        usersdoc=line.strip().split('-')
        username = usersdoc[0].strip()
        password = usersdoc[1].strip() if usersdoc[1] else ""
    

    Something I noticed that you may not have caught yet, because strip() comes before split(), your usernames and passwords can still have whitespace on either side if there's whitespace between the username/password and the dash.