How To Sort Data Alphabetically In A Csv File Created In Python?
Solution 1:
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.
Solution 2:
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']
Solution 3:
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.
Post a Comment for "How To Sort Data Alphabetically In A Csv File Created In Python?"