我想按日期对CSV表进行排序。开始是一项简单的任务:
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模块读取具有该结构的文件:
id;file;description;date;author;platform;type;port
最佳解决方案是让CSV客户端像数据库一样处理文件。我没有找到类似的东西。
我希望有人在这里知道一些不错的排序魔法;)
谢谢,
的Marius
答案 0 :(得分:57)
import operator
sortedlist = sorted(reader, key=operator.itemgetter(3), reverse=True)
或使用lambda
sortedlist = sorted(reader, key=lambda row: row[3], reverse=True)
答案 1 :(得分:11)
读者就像一个发电机。在包含一些虚假数据的文件中:
>>> import sys, csv
>>> data = csv.reader(open('data.csv'),delimiter=';')
>>> data
<_csv.reader object at 0x1004a11a0>
>>> data.next()
['a', ' b', ' c']
>>> data.next()
['x', ' y', ' z']
>>> data.next()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
将operator.itemgetter用作Ignacio建议:
>>> data = csv.reader(open('data.csv'),delimiter=';')
>>> import operator
>>> sortedlist = sorted(data, key=operator.itemgetter(2), reverse=True)
>>> sortedlist
[['x', ' y', ' z'], ['a', ' b', ' c']]
答案 2 :(得分:4)
按多列排序(按column_1
排序,然后按column_2
排序)
with open('unsorted.csv',newline='') as csvfile:
spamreader = csv.DictReader(csvfile, delimiter=";")
sortedlist = sorted(spamreader, key=lambda row:(row['column_1'],row['column_2']), reverse=False)
with open('sorted.csv', 'w') as f:
fieldnames = ['column_1', 'column_2', column_3]
writer = csv.DictWriter(f, fieldnames=fieldnames)
writer.writeheader()
for row in sortedlist:
writer.writerow(row)
答案 3 :(得分:0)
按列对 csv 进行排序,我会使用这样的东西
import pandas
csvData = pandas.read_csv('myfile.csv')
csvData.sort_values(["date"], axis=0, ascending=[False], inplace=True)
print(csvData)