decemberrobot decemberrobot - 4 years ago 194
JSON Question

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?

Answer Source

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)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download