decemberrobot
decemberrobot

Reputation: 531

List index out of range python in a for loop

I am trying to split the lines in a text document into an array, and append attributes to each of the values in the array before converting them to json to be displayed in a text file.

However, no matter how I tweak my codes, I still encounter the error " IndexError: list index out of range" for the fields1[1] line.

    with open(fileName,'r') as file:
    for line in file:
        if line.startswith('-') and 'section1' in line:
            for li in file:
                fields1 = li.split(',')
                testarr.append({
                "section1a": fields1[0],
                "section1b": fields1[1],
                "section1c": fields1[2]
                })      
                with open(test_dir,'a+') as test_file:
                    json.dump(testarr, test_file)

Any idea where the problem lies in?

Upvotes: 0

Views: 328

Answers (2)

voglster
voglster

Reputation: 833

You have some strange indenting and without the contents I'm not sure where your error would be, but this should help you find it:

testarr = []
with open(fileName,'r') as file:
    for line in file:
        if line.startswith('-') and 'section1' in line:
            fields1 = li.split(',')
            if len(fields1) >= 3:
                testarr.append(
                    {
                    "section1a": fields1[0],
                    "section1b": fields1[1],
                    "section1c": fields1[2]
                    }
                )
            else:
                print("This line has an error in it: {}".format(line))

with open(test_dir,'a+') as test_file:
    json.dump(testarr, test_file)

Upvotes: 2

kawadhiya21
kawadhiya21

Reputation: 2528

When you did li.split(','), it did not split into 3 parts. May be it did not have enough , to split. For example .. li = 'asdf,ffd' This will give error on fields1[2] because it will split into 2 parts only ['asdf', 'ffd'].

Upvotes: 2

Related Questions