I have a txt file with names and dates like this
name0 - 05/09/2020
name1 - 14/10/2020
name2 - 02/11/2020
How can I sort the text file by date? so that the file will end up like this
name2 - 02/11/2020
name1 - 14/10/2020
name0 - 05/09/2020
(I use dd/mm/yyyy)
You can use the datetime
module to do this, along with the builtin reading functionality:
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))