Is it possible to sort a csv file in python by data? -
is possible sort csv file in python average, alphabetical order etc. right have simple print row code , wondering if it's possible sort data. (name, class , score) it's task can't display code here, answers appreciated.
if looking sorting of csv file based on columns, here quick solution:
import csv import operator # sort based on 3 column, iteration starts @ 0 (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 @ 0 (0) r=csv.reader(open("1.csv"), delimiter=",") print("\nsorted based on 2nd column") print(sorted(r, key=operator.itemgetter(1), reverse=true))
suppose csv mentioned below
$> cat 1.csv 1,a,32,hello 2,x,33,xello 3,h,23,belo 4,z,3,elo
then when run 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 looking for?
Comments
Post a Comment