I am trying to read a CSV file into a list and then sort it based on the first two columns of the list (first by first column and then by second column if the first column is the same). This is what I am doing:
def sortcsvfiles(inputfilename,outputfilename):
list1=[]
row1=[]
with open(inputfilename,'rt') as csvfile1:
reader=csv.reader(csvfile1)
cnt=0
for row in reader:
if cnt==0: #skip first row as it contains header information
row1=row
cnt+=1
continue
list1.append((row))
list1.sort(key=lambda ro: (int(ro[0]),int(ro[1])))
list1.insert(0, row1)
with open(outputfilename,'wt') as csvfile1:
writer=csv.writer(csvfile1, lineterminator='\n')
for row in list1:
writer.writerow(row)
But I am getting the following error:
File "C:\Users\50004182\Documents\temp.py", line 37, in <lambda>
list1.sort(key=lambda ro: (int(ro[0]),int(ro[1])))
IndexError: list index out of range
How can I fix this?