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

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

3 Comments

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?
'for row in reader: _csv.Error: new-line character seen in unquoted field - do you need to open the file in universal-newline mode?'
ok, try open('file.csv', 'rU') and tell me (I don't have your file) (stackoverflow.com/questions/17315635/…)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.