python csv sort by column

python csv sort by column

if you want to sort your csv file by specific column , you can do it very easily with python. yo only need to import operator library. so let me explain it better with an explain:

import csv import operator

try:                #open data file for reading                f = open(FILE_NAME, ‘r’)                reader = csv.reader(f,DELIMITER)

except:                print(“can not read the file”)

sortedlist = sorted(reader, key=lambda d: int(d[COLUMN_NO])) f.close()

#writing to csv result = open(FILE_NAME,”w”) result_writer=csv.writer(result,DELIMITER)

#write list to csv   result_writer.writerows(sortedlist)

** **

it was the program which sort your file. if you want to give the column name you should change only this line:

**sortedlist = sorted(reader, key=lambda d: str(d[‘COLUMN_NAME’])) **