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)
Just reading the error, keyerror: 2, my eye goes to , datetime.strptime(row[2]).
You're trying to use a 0-based column index number for a DictReader, which expects a column name (which is derived from the first line (row) of data in your file, which it expects to be a "header").
So, swap row[2] out for row['third_column_name'] and you should be good.
If you don't have a header, use csv.reader().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With