Error with line splitter code

This is the place for queries that don't fit in any of the other categories.

Error with line splitter code

Postby mattster2020 » Tue Sep 27, 2016 10:53 am

Hi All,

I am trying to get the below code working:
Code: Select all
import csv
newrows = []

def chrow(row, idx):
    n = []
    n.append(row[0])
    if idx==0:
        n.append(row[1])
    elif idx==1:
        n.append(row[1].split(',')[0])
    else:
        n.append(row[1].split(',')[1])
    n.append(row[3][:10])
    n.append(row[3][11:])
    n.append(row[4][11:])
    n.append(row[6])
    return n

with open('input.csv','rt') as csvfile:
    r = csv.reader(csvfile,delimiter=',',quotechar='"')
    for row in r:
        if ',' in row[1]:
            newrows.append(chrow(row,1))
            newrows.append(chrow(row,2))
        else:
            newrows.append(chrow(row,0))

sortedList = sorted(newrows[1:], key=lambda row: row[2])

with open('output.csv','wb') as outcsvfile:
    w = csv.writer(outcsvfile, delimiter=',',quotechar='"',quoting=csv.QUOTE_ALL)
    for new in sortedList:
        w.writerow(new)

Im getting the following error when executing the script:
Code: Select all
if ',' in row[1]:
IndexError: list index out of range

Can anyone provide any help as to why this error is caused?

Regards,

Matt
Last edited by Yoriz on Tue Sep 27, 2016 11:50 am, edited 1 time in total.
Reason: First post lock. Added code tags.
mattster2020
 
Posts: 1
Joined: Tue Sep 27, 2016 10:48 am

Re: Error with line splitter code

Postby Ofnuts » Tue Sep 27, 2016 4:36 pm

If your row has only one element, row[1] is out of range (the first element is row[0]). You can even get an empty row in which case even row[0] is out of range.
This forum has been moved to http://python-forum.io/. See you there.
User avatar
Ofnuts
 
Posts: 2659
Joined: Thu May 14, 2015 9:46 am
Location: Paris, France, EU, Earth, Solar system, Milky Way, Local Cluster, Universe #32987440940987


Return to General Coding Help

Who is online

Users browsing this forum: No registered users and 5 guests