Reputation: 121
I want to sort the data in a csv file alphabetically according to the contents in the first column. For example, if the file contained:
city/month,Jan,Feb,Mar,Apr
Melbourne,41.2,35.5,37.4,29.3
Brisbane,31.3,40.2,37.9,29
Darwin,34,34,33.2,34.5
it would be sorted as:
city/month,Jan,Feb,Mar,Apr
Brisbane,31.3,40.2,37.9,29
Darwin,34,34,33.2,34.5
Melbourne,41.2,35.5,37.4,29.3
what I've done so far, sorts correctly but it doesn't return the answer correctly, instead of returning it in the table format, it returns everything as a list - any idea why that is?
import csv
import operator
def sort_records(csv_filename, new_filename):
f = open(csv_filename)
csv1 = csv.reader(f, delimiter = ',')
new_filename = sorted(csv1)
return new_filename
f.close()
Upvotes: 2
Views: 750
Reputation: 52143
>>> import csv
>>> import operator
>>> def sort_records(csv_filename, new_filename):
... with open(csv_filename, 'r') as i, open(new_filename, 'w') as o:
... reader = csv.reader(i, delimiter = ',')
... writer = csv.writer(o, delimiter=',')
... writer.writerow(next(reader)) # header row
... writer.writerows(sorted(reader, key=operator.itemgetter(0)))
>>> sort_records('a.csv', 'b.csv')
Upvotes: 4