1

The name of a user and their score from a quiz is entered in a csv file. I want to sort the name of the user alphabetically, however I don't know how to do this. Thanks in advance. Here are snippets of my code.

userName=input('Please enter your full name: ').title()
newrecord = "{user_name},{score_1},{score_2},{score_3}\n".format(user_name=userName, score_1=quiz_scores[0], score_2=quiz_scores[1], score_3=quiz_scores[2])
classa = input("What class are you in? ")
if classa =='1':
    file=open('classroom1.csv', "a+")
    file.write(newrecord)
    file.close()
    with open('classroom1.csv') as csvfile:
        readCSV = csv.reader(csvfile)
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
Bob Stanley
  • 49
  • 3
  • 11

3 Answers3

0

I'm assuming that given a csv file of user names and quiz scores, you want to read the csv file and then sort based on user names. Your problem (I believe) is that each time you read from the csv file, you get a list of the form [user_name, score1, score2, score3].

If so, why not store each such list in a dictionary, using the user_names as keys, and then sort the dictionary keys - i.e.

sorting_dict = {}
for curr_elem in readCSV:
   sorting_dict[curr_elem[0]] = curr_elem #Note this assumes no 2 users have the same name
sorted_names = sorted(sorting_dict.keys()) # actually sorted(sorting_dict) will also work and may be preferred, but '.keys()' makes it clearer for me

Now, you can access your records in sorted order:

for curr_user in sorted_names:
   curr_record = sorting_dict[curr_user]
   #Do what you want from here...

====================================================

Hmmmmm... it's odd this didn't work for you. I made a dummy file like you described and this is what seemed to work for me:

>>> f=open('csv.txt','r')
>>> readCSV = csv.reader(f)
>>> for curr_elem in readCSV:
...     sorting_dict[curr_elem[0]] = curr_elem
... 
>>> sorted_names = sorted(sorting_dict.keys())
>>> sorted_names
['art', 'bob', 'dick', 'harry', 'tom']
>>> for curr_user in sorted_names:
...     print sorting_dict[curr_user]
... 
['art', '77', '99', '98']
['bob', ' 88', '99', '78']
['dick', '77', '66', '99']
['harry', '90', '78', '98']
['tom', '33', '98', '67']
>>> 

where my csv.txt file was:

bob, 88,99,78
art,77,99,98
tom,33,98,67
dick,77,66,99
harry,90,78,98

the only 'gotcha' here is you need to be sure the 'harry' line doesn't end with a \n, otherwise the csv reader will read an empty line that will throw an error at sorting_dict[curr_elem[0]] = curr_elem, but one can easily guard against that.

user1245262
  • 6,968
  • 8
  • 50
  • 77
  • I have tried this code however nothing is being printed. I have used that code but added print(curr_record) at the end – Bob Stanley Dec 26 '15 at 19:47
  • @BobStanley - Odd it doesn't work for you. I expanded my answer a little to show how it works for me. Hope that helps. – user1245262 Dec 27 '15 at 00:55
0

Consider using the list.sort() function by appending csv data into a list and then sorting it by first element using a defined function. This function might even be unnecessary as Python defaults to first element in nested list, so can leave out the key argument:

csvdata = []
with open('classroom1.csv') as csvfile:
        readCSV = csv.reader(csvfile)        
        for line in readCSV:
            csvdata.append(line)

for i in csvdata:
    print(i)
#['bravo', '93']
#['alpha', '86']
#['charlie', '67']
#['echo', '70']
#['delta', '75']

def getKey(item):
    return item[0]    

csvdata.sort(key=getKey)

for i in csvdata:
    print(i)
#['alpha', '86']
#['bravo', '93']
#['charlie', '67']
#['delta', '75']
#['echo', '70']
Parfait
  • 104,375
  • 17
  • 94
  • 125
0

Why not use Pandas?

df = pd.read_csv('classroom1.csv', sep = ',', names = ['user_name','score_1','score_2','score_3'])
df = df.sort('user_name')
df.to_csv('classroom1.csv', index = False, header = False)

That should take care of it.

ZeerakW
  • 323
  • 1
  • 3
  • 9