here is my code.csv
one,two #read the headers from here, and if the code finds headers,
1,2 #it takes the columns of the old headers, to the new headers in a new order.
2,3
3,4
for example, the output.csv would look like this:
new_two,new_one,new_three
2,1
3,2
4,3
notice there is missing the ",three" after two. This is my python code:
import csv
with open('code.csv', 'rb') as input, open('result.csv', 'wb') as output:
reader = csv.DictReader(input)
rows = [row for row in reader]
writer = csv.writer(output, delimiter = ',')
writer.writerow(["new_two", "new_one", "new_three"])
for row in rows:
if row['one'] and row['two'] and row['three'] not in row:
pass
else:
writer.writerow([row["one"], row["two"], row["three"]])
Basically i want my code to always have this part: writer.writerow([row["one"], row["two"], row["three"]]), that takes the columns from input file headers, but if it doesn't find one of those headers,I want it to forget that and continue on with the rest of the columns.
it gives me this error:
Traceback (most recent call last):
File "my_code.py", line 11, in <module>
if row['one'] and row['two'] and row['three'] not in row:
KeyError: 'three'