简体   繁体   中英

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 (eg 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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM