sort csv by column
To sort by MULTIPLE COLUMN (Sort by column_1
, and then sort by column_2
)
with open('unsorted.csv',newline='') as csvfile:
spamreader = csv.DictReader(csvfile, delimiter=";")
sortedlist = sorted(spamreader, key=lambda row:(row['column_1'],row['column_2']), reverse=False)
with open('sorted.csv', 'w') as f:
fieldnames = ['column_1', 'column_2', column_3]
writer = csv.DictWriter(f, fieldnames=fieldnames)
writer.writeheader()
for row in sortedlist:
writer.writerow(row)
import operator
sortedlist = sorted(reader, key=operator.itemgetter(3), reverse=True)
or use lambda
sortedlist = sorted(reader, key=lambda row: row[3], reverse=True)