The following script is erroring out:
import csv,time,string,os,requests, datetime
test = "\\\\network\\Shared\\test.csv"
fields = ["id", "Expiration Date", "Cost", "Resale" ]
with open(test) as infile, open("c:\\upload\\tested.csv", "wb") as outfile:
r = csv.DictReader(infile)
w = csv.DictWriter(outfile, fields, extrasaction="ignore")
r = (dict((k, v.strip()) for k, v in row.items() if v) for row in r)
wtr = csv.writer( outfile )
wtr.writerow(["id", "upload_date", "cost", "resale"])
for i, row in enumerate(r, start=1):
row['id'] = i
print(row['Expiration Date']
row['Expiration Date'] = datetime.datetime.strptime(row['Expiration Date'][:10], "%m/%d/%Y").strftime("%Y-%m-%d")
w.writerow(row)
D:\Python\Scripts>python test.py
Traceback (most recent call last):
File "test.py", line 18, in <module>
print(row['Expiration Date'])
KeyError: 'Expiration Date'
So I think I understand what's going on - something like this from the original file:
Expiration Date Cost Resale
2016-01-01 1.00 2.00
1.42 2.42
2016-05-02 1.45 9.00
From what I can gather, there is a row where the expiration date column is NOT populated. How do I force DictWriter to skip over blanks - assuming that is the cause of my error?