Search code examples
pythonpython-3.xindex-error

List index out of range when appending text from files


The code below throws an IndexError saying list index out of range but when I print the item on that index, it shows that there is text there.

So why am I getting an index error?

code:

paths = []
formats = []

with open("config.cf","r") as config_file:

    global sort_mode
    sort_mode = config_file.readline().replace("\n","").split(":")

    if sort_mode[1] == "custom":

        for line in config_file:

            temp = str(line).replace("\n","").split("/")

            if temp[0] == "mode:":
                continue

            format_list = str(temp[0]).split(",")

            paths.append(temp[1]) # <---- Error
            formats.append(format_list)

the first line of the "Config file" is mode:custom and the second is .txt/text

When i do print(temp[1]) i get "text" and the "index error" at the same time.


Solution

  • You file contains a \n at the end of it - the line after is "empty".

    This temp = str(line).replace("\n","").split("/") returns a list with 1 element.

    Afterwards you access this list with temp[1] - this causes the indexing error.

    Next time you get such an error, replace the access-line with a print of the list, this gives you a good idea whats wrong.

    Use

    if len(temp) < 2 or temp[0] == "mode:":
        continue 
    

    Empty lists are falsy and it would continue afterwards.

    The other thing you can always do if you encounter exceptions: catch them.

    try:
    
        print( [][20])
    except IndexError as e:
        print(e)
    

    Code to test it (use first the one then the other create-code for config.cf):

    # works
    with open("config.cf","w") as f:
        f.write("""mode:custom
    .txt/text""")
    
    # fails
    with open("config.cf","w") as f:
        f.write("""mode:custom
    .txt/text
     """)