Jefer Bulan
Jefer Bulan

Reputation: 43

IndexError: tuple index out of range in showing columns of CSV

Guys i am new in python and i dont know how to solve the problem. Thanks for the help guys.

import csv

with open("ict.csv", 'r') as csvFile:
    csvRead = csv.reader(csvFile)
    print(csvRead)

#    for line in csvRead :
 #       print(line)

    header = csvFile.readline().strip().split(',')
    print(header)

    entries = []
    for line in csvFile:

        parts = line.strip().split(',')
        row = dict()
        for i, h in enumerate(header):
            row[h] = parts[i]

#        print(row)

        entries.append(row)

    entries.sort(key= lambda r: r['Gen. Ave.'])

    for e in entries [:12]:
        print('{0}Student No.,Gen. Ave. {10:,}'.format(
            e['Student No.'],e['Gen. Ave.']
        ))

Student No. | Gen. Ave. | Program 1 | 90.5 | CS

Upvotes: 3

Views: 546

Answers (2)

snakecharmerb
snakecharmerb

Reputation: 55724

The problem, as pointed out in the comments, is that one of your format specifiers - {10:,} - is wrong. The initial 10 is telling Python to use the 10th argument provided to format, but you have only provided two, hence the IndexError.

You actually want to provide the second element of the tuple, at index 1, so change to {10:,} to {1:,}. Also, the comma (,) operator in the format string - telling the formatter to use a comma as the thousand separator - can only be used on numeric inputs. The value of entries['Gen. Ave.'] is a string, because it's been read from a file, so you need to convert it to a number. This code should work:

for e in entries [:12]:
    print('{0}Student No.,Gen. Ave. {1:,}'.format(
        e['Student No.'], int(e['Gen. Ave.'])
    ))

However the position specifiers in your format strings can be removed completely, because Python will use apply the arguments to format in the order that they are written, so you can have:

for e in entries [:12]:
    print('{}Student No.,Gen. Ave. {:,}'.format(
        e['Student No.'], int(e['Gen. Ave.'])
    ))

Finally, you can avoid manually building dicts for each row in your csv by using the csv module's DictReader class, which will create a dict for each row as it's read, leaving your code looking like this:

 with open("ict.csv", 'r') as csvFile:
    csvRead = csv.DictReader(csvFile)

    entries = []
    for line in csvRead:
        entries.append(line)

entries.sort(key=lambda r: r['Gen. Ave.'])

for e in entries[:12]:
    print('{}Student No.,Gen. Ave. {:,}'.format(e['Student No.'], int(e['Gen. Ave.'])))

Upvotes: 1

andreihondrari
andreihondrari

Reputation: 5833

First of all, you are not using the csvRead instance. You should be reading from it instead of the csvFile.

Example:

I have the following something.csv CSV file:

76.94,76.944,76.945
76.97,76.979,76.980
77.025,77.025,77.025
77.063,77.264,77.064
77.1,77.64,77.3

Now if I do:

import csv

pf = open("something.csv", "r")

read = csv.reader(pf)

for r in read:
    print(r)

pf.close()

You will get the following output:

python your_script.py                                                                                                                                                                                  
['76.94', '76.944', '76.945']
['76.97', '76.979', '76.980']
['77.025', '77.025', '77.025']
['77.063', '77.264', '77.064']
['77.1', '77.64', '77.3']

Upvotes: 0

Related Questions