HannaG
HannaG

Reputation: 11

Sorting CSV file alphabetically using Python

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)

Upvotes: 0

Views: 2826

Answers (1)

Cyrbil
Cyrbil

Reputation: 6478

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

Upvotes: 1

Related Questions