I try to use Python to sort a csv file by date (newest entries first). The column of the csv file that contains dates is the third column of the csv file.
When I run the code below, I get the following error message:
KeyError: 2
Could you please provide me guidelines to correct my script below:
import csv
import os
from csv import writer
from datetime import datetime
with open("data.csv", newline="") as csvfile:
spamreader = csv.DictReader(csvfile, delimiter=",")
sortedlist = sorted(spamreader, key=lambda row: datetime.strptime(row[2]), reverse=False)
with open("sortdata.csv", "w") as f:
fieldnames = ["detection_date"]
writer = csv.DictWriter(f, fieldnames=fieldnames)
writer.writeheader()
for row in sortedlist:
writer.writerow(row)