【问题标题】:how to sort a csv file by columns and then output the result to a file [duplicate]如何按列对csv文件进行排序,然后将结果输出到文件[重复]
【发布时间】:2014-03-30 00:45:59
【问题描述】:

第 4 列有出生日期 (dd/mm/yyyy)。我希望此列按升序排序;然后输出到一个文件中。

请帮忙

【问题讨论】:

  • 你试过什么? DOB的格式是什么?请发布示例输入
  • 您需要将所有出生日期读入一个列表,对列表进行排序,然后输出该列表。
  • 我编辑了它,现在它显示了DOB的格式

标签: python csv


【解决方案1】:
import csv
from datetime import datetime
with open('path/to/file') as infile, open('path/to/output', 'w') as outfile:
    rows = [line for line in csv.reader(infile)]
    rows.sort(key=lambda row:datetime.strptime(row[3], "%d/%m/%Y"))
    writer = csv.writer(outfile)
    writer.writerows(rows)

【讨论】:

  • 谢谢,但第 5 行的 lamda 是什么?
  • @ap306:该 lambda 将第 4 列转换为机器可解析的日期/时间,以便进行排序
猜你喜欢
  • 2015-12-24
  • 2021-09-04
  • 2017-08-01
  • 2015-10-29
  • 1970-01-01
  • 1970-01-01
  • 2013-12-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多