1

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'

1 Answer 1

1

While syntactically valid, the

row['one'] and row['two'] and row['three'] not in row

doesn't do what you are expecting it to.

To check that row contains the keys 'one', 'two' and 'three', use

if 'one' in row and 'two' in row and 'three' in row:
   writer.writerow([row['one'], row['two'], row['three']])

In case you're wondering about your original code, the if is parsed as

if (row['one']) and (row['two']) and (row['three'] not in row):

In other words, the row['one'] and row['two'] are treated as separate expressions that are ANDed together. This clearly isn't what you want. Besides, you've got your ANDs and ORs mixed up (my version uses AND because I've reversed the check, placing the writerow() in the if rather than the else).

Sign up to request clarification or add additional context in comments.

1 Comment

Your code worked almost. It now prints out new_two,new_one,new_three 1,2,['three'] 2,3,['three'] 3,4,['three'] while i want the output to be new_two,new_one,new_three 1,2 2,3 3,4

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.