简体   繁体   中英

How to sort data alphabetically in a csv file created in python?

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)

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 - ie

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.

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']

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM