user6040312
user6040312

Reputation:

Fixing outputting csv file in alphabetical order in python

My code should output a column of the csv file called name in alphabetical order. It comes up with list index out of range.

filename = class_name + ".csv"
csv.register_dialect('pipes', delimiter='|')

with open(filename, 'a',newline='') as fp:
    a = csv.writer(fp, delimiter=',')
    data=(name,score)              
    a.writerow(data)


if get_bool_input("Do you wish to view previous results for your class"):
    with open(filename, 'r') as f:
        reader = csv.reader(f, dialect = 'pipes')
        sortedlist = sorted(reader, key=operator.itemgetter(3), reverse=True)
        for row in reader:
            print (row)
else:
    input ("Press any key to exit")

Upvotes: 0

Views: 738

Answers (1)

Edward Carney
Edward Carney

Reputation: 1392

The code below will open the file, read up the header determine the index of the "Name" column, extract all the names and return a sorted list of the names.

The data file looks like this:

Name    Score
Liam    95
Mason   87
Jacob   67
William 86
Ethan   75
Michael 94
Alexander   84
James   88
Daniel  64
Olivia  100
Sophia  86
Isabella    100
Ava 82
Mia 91
Emily   99
Abigail 82
Madison 91
Charlotte   99

Here's the code:

import csv
filename = 'soc153.csv'
def get_names(filename):
    in_list = []
    with open(filename, 'r') as f:
        reader = csv.reader(f)
        header_line = next(reader)
        name_column = header_line.index('Name')
        for row in reader:
            in_list.append(row[name_column])
    return(sorted(in_list))
if input("Do you wish to view previous results for your class?") == 'y':
    name_list = get_names(filename)

This produces the following values in name_list:

['Abigail', 'Alexander', 'Ava', 'Charlotte', 'Daniel', 'Emily', 'Ethan', 'Isabella', 'Jacob', 'James', 'Liam', 'Madison', 'Mason', 'Mia', 'Michael', 'Olivia', 'Sophia', 'William']

Upvotes: 2

Related Questions