按列对csv进行排序 [英] sort csv by column

查看:54
本文介绍了按列对csv进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想按日期对 CSV 表进行排序.开始是一项简单的任务:

I want to sort a CSV table by date. Started out being a simple task:

import sys
import csv

reader = csv.reader(open("files.csv"), delimiter=";")

for id, path, title, date, author, platform, type, port in reader:
    print date

我使用 Python 的 CSV 模块读取具有该结构的文件:

I used Python's CSV module to read in a file with that structure:

id;file;description;date;author;platform;type;port

  • 日期是 ISO-8601,因此我可以很容易地对其进行排序而无需解析:2003-04-22 e.g.
  • 我想按日期排序,最新的条目在前
  • 如何让这个阅读器进入可排序的数据结构?我想通过一些努力,我可以制作一个日期列表:日期列表 += 日期,拆分和排序.但是,我必须重新识别 CSV 表中的完整条目.这不仅仅是对事物列表进行排序.
  • csv 似乎没有内置的排序功能
  • 最佳解决方案是拥有一个像处理数据库一样处理文件的 CSV 客户端.我没有找到类似的东西.

    The optimal solution would be to have a CSV client that handles the file like a database. I didn't find anything like that.

    我希望有人在这里知道一些不错的排序魔法;)

    I hope somebody knows some nice sorting magic here ;)

    推荐答案

    import operator
    sortedlist = sorted(reader, key=operator.itemgetter(3), reverse=True)
    

    或使用 lambda

    sortedlist = sorted(reader, key=lambda row: row[3], reverse=True)
    

    这篇关于按列对csv进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆