Sorting csv data

Question:

The ask is to sort and save a csv file in a new csv file. With the code below(below1), I seem to get the result when I open the new csv file. However, when I run the code on the homework interface, it prints out wrong (below2). Can anyone identify why it doesn’t work? I have the correct solution to the ask as well (below3). I don’t understand why mine doesn’t work.

Below1:

import csv
def sort_records(csv_filename, new_filename):
    file = open(csv_filename)
    lines = file.readlines()
    newfile = open(new_filename, "w")
    header = lines[0]
    newfile.write(header)
    lines.remove(header)
    lines.sort(key=lambda x: x[0])
    for item in lines:
        newfile.write(item)
    file.close()
    newfile.close()

Below2:

city/month,Jan,Feb,Mar,Apr
Brisbane,31.3,40.2,37.9,29
Darwin,34,34,33.2,34.5Melbourne,41.2,35.5,37.4,29.3

Below3:

import csv
def sort_records(csv_filename, new_filename):
    csv_file = open(csv_filename)
    reader = csv.reader(csv_file)
    header = next(reader)
    data2d = list(reader)
    data2d.sort()
    csv_file.close()
    new_file = open(new_filename, "w")
    writer = csv.writer(new_file)
    writer.writerow(header)
    writer.writerows(data2d)
    new_file.close()

The original csv file:

city/month,Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec
Melbourne,41.2,35.5,37.4,29.3,23.9,16.8,18.2,25.7,22.3,33.5,36.9,41.1
Brisbane,31.3,40.2,37.9,29,30,26.7,26.7,28.8,31.2,34.1,31.1,31.2
Darwin,34,34,33.2,34.5,34.8,33.9,32,34.3,36.1,35.4,37,35.5
Perth,41.9,41.5,42.4,36,26.9,24.5,23.8,24.3,27.6,30.7,39.8,44.2
Adelaide,42.1,38.1,39.7,33.5,26.3,16.5,21.4,30.4,30.2,34.9,37.1,42.2
Canberra,35.8,29.6,35.1,26.5,22.4,15.3,15.7,21.9,22.1,30.8,33.4,35
Hobart,35.5,34.1,30.7,26,20.9,15.1,17.5,21.7,20.9,24.2,30.1,33.4
Sydney,30.6,29,35.1,27.1,28.6,20.7,23.4,27.7,28.6,34.8,26.4,30.2

Asked By: aadyali

||

Answers:

I’ve run your code on my machine and it works as it’s supposed to. Is it possible to print out the CSV file from this homework interface before sorting?

Answered By: Cezary Sawicki

There is no need for additional modules in this case. Open the input file for reading (readonly) and the output file for writing.

Write the first line (column descriptions) from input to output. Then sort the list returned from readlines and write to output.

Like this:

ORIGINAL = 'original.csv'
NEW = 'new.csv'

with open(ORIGINAL) as original, open(NEW, 'w') as new:
    new.write(next(original))
    new.writelines(sorted(original.readlines(), key=lambda x: x.split(',')[0]))
Answered By: OldBill
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.