首页 > 解决方案 > 在文件中排序日期(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)

标签: python

解决方案


您可以使用该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))

推荐阅读