python - 在文件中排序日期(Python)
问题描述
我有一个 txt 文件,其中包含这样的名称和日期
名称0 - 05/09/2020
名称1 - 2020 年 10 月 14 日
名称 2 - 2020 年 2 月 11 日
如何按日期对文本文件进行排序?这样文件就会像这样结束
名称 2 - 2020 年 2 月 11 日
名称1 - 2020 年 10 月 14 日
名称0 - 05/09/2020
(我使用 dd/mm/yyyy)
解决方案
您可以使用该datetime
模块以及内置的阅读功能来执行此操作:
from datetime import datetime
# Read in the file
with open("file.txt", "r") as infile:
contents = infile.readlines()
contents = [c.strip() for c in contents]
# Grab the dates
dates = [line.split("-")[1].strip() for line in contents]
dates = [datetime.strptime(d, "%d/%m/%Y") for d in dates]
# Zip contents and dates together
zipped = list(zip(contents, dates))
# Sort them
sorted_zipped = sorted(zipped, key = lambda x: x[1], reverse=True)
# Unzip them and grab the sorted contents
sorted_contents = next(zip(*sorted_zipped))
# Write the sorted contents back out
with open("outfile.txt", "w") as out:
out.write("\n".join(sorted_contents))
推荐阅读
- javascript - 比较两个对象以获得匹配的元素
- c# - 如何在 C# 中从网络摄像头解码 QR_CODE?
- nuget - FlowDocument .NET Core 3 的 NuGet 包
- swift - 带有 Firestore 的自定义模型
- matlab - Matlab Enframe 整数只能与同一类的整数组合
- kotlin - 是否可以在 kotlin 中嵌套数据类?
- reactjs - 如何修复:第二次调用 React 时,渲染方法的返回部分中的变量未更新
- vba - 如何将记录集中文本框的值设置为超链接地址?
- c# - 使用 Coypu 禁用 Chrome 自动化扩展
- c# - 关键字 yield 如何记住下一条要执行的指令以及在控制权被归还的那一刻的堆栈帧状态?