Reputation: 65
I have this piece of code written to sort a csv file in Python.
import csv
from operator import itemgetter
reader = csv.reader(open("highscores.txt"), delimiter=",")
sortedList = sorted(reader, key=itemgetter(1), reverse=True)
print(sortedList)
I am trying the sort the file by the second item in the array, for example if in my file I had:
Callum,22
Kim,43
It would sort it to:
Kim,43
Callum,22
However when I run my program I get the error message:
sortedList = sorted(reader, key=itemgetter(1), reverse=True)
IndexError: list index out of range
Edit:
I have solved this issue, the problem wasn't the sort function itself but it was a problem with the file that only worked in python 2.7 for some reason.
Upvotes: 1
Views: 3219
Reputation: 27869
My assumption is that you are missing some data. Here is my workaround for that case:
import csv
with open("highscores.txt") as data:
data = csv.reader(data)
data = [item for item in data]
for i, item in enumerate(data):
try:
item = int(item[1])
except:
data[i].append('0')
items = sorted(data, key=lambda x: int(x[1]), reverse=True)
print(items)
Upvotes: 0
Reputation: 1015
You can use lambda which will allow you to do type transform etc. Similar to your example above, following lines will do what you want (I have kept sort etc default):
r = csv.reader(open("test.txt"))
sorted(r, key=lambda x: int(x[1]))
You can read more details at https://wiki.python.org/moin/HowTo/Sorting
These are full details showing version and platform:
Python 2.7.10 (default, Jul 30 2016, 18:31:42)
[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.34)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import csv
>>> r = csv.reader(open("test.txt"))
>>> sorted(r, key=lambda x: int(x[1]))
[['Can', ' 2'], ['Try', ' 5'], ['Science', ' 12'], ['Math', ' 22'], ['Life', ' 35']]
where test.txt is as below:
Science,12
Math,22
Life,35
Can,2
Try,5
Upvotes: 1