0

Can someone please tell me how to sort a CSV file alphabetically in columns when the data comes from multiple variables (e.g name and age)? I need names to be displayed in alphabetical order.

Here is my code:

with open ("Information.csv", "a", newline="",) as CSVFile:
    for_use = csv.writer (CSVFile, delimiter=",")
    info = [[name, age]]
    for_use.writerows(info)
2
  • 1
    You will have to 1) read the entire CSV into memory, 2) sort it, 3) output it back into a CSV file. You can't really "sort a file" on disk. Commented Nov 16, 2015 at 12:24
  • Thank you for your quick reply, that helps. Commented Nov 16, 2015 at 12:28

1 Answer 1

1

You can read as a dict then sort like you sort a dict ...

import csv
with open('Information.csv') as csvfile:
    reader = csv.DictReader(csvfile)

    sorted = sorted(reader,
                key=lambda k: (k['name'].lower(), k['age'])) # sorting by name and age

sorted will be a generator that yields all items sorted

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

4 Comments

Gave me an error AttributeError: 'DictReader' object has no attribute 'items'
Oups, remove .items()
ValueError: I/O operation on closed file. Does not work!
Oups again, moved the operation inside the with statement

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.