简体   繁体   中英

Is it possible to sort a csv file in python by data?

Is it possible to sort a csv file in python by an average, alphabetical order etc. Right now I have a simple print row code and am wondering if it's possible to sort the data. (Name, class and score) It's for a task so I can't display my code here, so all answers are appreciated.

If you are looking for sorting of a csv file based on columns, here is a quick solution:

import csv
import operator

# Sort based on 3 column, iteration starts at zero (0)
r=csv.reader(open("1.csv"), delimiter=",")
print("Sorted based on 3rd column")
print(sorted(r, key=operator.itemgetter(2), reverse=True))

# Sort based on 2 column, iteration starts at zero (0)
r=csv.reader(open("1.csv"), delimiter=",")
print("\nSorted based on 2nd column")
print(sorted(r, key=operator.itemgetter(1), reverse=True))

Suppose your csv is as mentioned below

$> cat 1.csv 
1,a,32,hello
2,x,33,xello
3,h,23,belo
4,z,3,elo

Then when you run the above code:

$> python ./sort.py
Sorted based on 3rd column
[['2', 'x', '33', 'xello'], ['1', 'a', '32', 'hello'], ['4', 'z', '3', 'elo'], ['3', 'h', '23', 'belo']]

Sorted based on 2nd column
[['4', 'z', '3', 'elo'], ['2', 'x', '33', 'xello'], ['3', 'h', '23', 'belo'], ['1', 'a', '32', 'hello']]

Is this what you were looking for?

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