0

My lessons with python continues and im stuck with this exercise where i have such csv:

John^Reporter^Angola
Mary^Engineer^Canada
Anna^Manager^India

and would like to achieve this:

Angola^John^Reporter
Canada^Engineer^Mary
Anna^India^Manager

so every row is sorted by content in column from left to right.

I tried with this code:

with open('file.csv', 'r') as sortrow:
    reader = csv.reader(sortrow.readlines(), delimiter='^')
    reader = sorted(reader, key=lambda x: x[0])
    with open(syspath+temppath+'/added5.csv', 'w') as sortwrite:
        writer = csv.writer(sortwrite, delimiter='^')
        for row in reader:
            writer.writerow(row)

i thought sorted(reader, key=lambda x: x[0]) will do the job but its not. Please help. Thanks in advance

Lucas
  • 93
  • 2
  • 12

1 Answers1

1

With reader = sorted(reader, key=lambda x: x[0]), your key is the first column (x[0]).

In your case you don't want to sort the rows but the columns, so

1) don't sort the reader

2) just do this:

    for row in reader:
        writer.writerow(sorted(row))

full fixed code:

with open('file.csv', 'rU') as sortrow:
    reader = csv.reader(sortrow, delimiter='^')  # don't use readlines()
    with open(syspath+temppath+'/added5.csv', 'w', newline='') as sortwrite:
        writer = csv.writer(sortwrite, delimiter='^')
        for row in reader:
            writer.writerow(sorted(row))  # sort done here

note that if there was a consistency between the data of the same columns, it is lost by the column sort

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
  • so this line `reader = sorted(reader, key=lambda x: x[2])` is always sorting columns? then how to sort every row from left to right? – Lucas Dec 21 '16 at 09:15
  • 'for row in reader: _csv.Error: new-line character seen in unquoted field - do you need to open the file in universal-newline mode?' – Lucas Dec 21 '16 at 10:12
  • ok, try `open('file.csv', 'rU')` and tell me (I don't have your file) (http://stackoverflow.com/questions/17315635/csv-new-line-character-seen-in-unquoted-field-error) – Jean-François Fabre Dec 21 '16 at 10:15