0

I'm using excel to store a username and score. For example:

Ben,1 

Kim,9

Jeff,3

Bob,5

I would like to sort them using the score highest to lowest but I keep getting this error:

list index out of range

My code:

import csv

import operator

sample = open("data.csv","r")

reader = csv.reader(sample,delimiter=',')

sort = sorted(reader,key=operator.itemgetter(1))
1
  • On which line do you get the error? Posting the error without code-line reference is not really useful. Commented Jan 31, 2019 at 11:29

1 Answer 1

1

You are getting the error because of the empty line

import csv
import operator

result = []
with open(filename) as infile:
    reader = csv.reader(infile,delimiter=',')
    for line in reader:
        if line:                #Check if line is empty
            result.append(line)

print(sorted(result,key=operator.itemgetter(1)))

or use filter

with open(filename) as infile:
    reader = csv.reader(infile,delimiter=',')
    print( sorted(filter(None, reader),key=operator.itemgetter(1)) )
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.