0

This is my code thus far:

with open('in.csv', 'rb') as inp, open('out.csv', 'wb') as out:
    writer = csv.writer(out)
    for row in csv.reader(inp):
        try:
            floatRow= float(row[3].strip())
            if  floatRow > 180.0:
                row[3] = floatRow - 180.0
                writer.writerow(row)
            else:
                if floatRow < 180.0:
                    row[3] = floatRow + 180.0
                else:
                    writer.writerow(row)

        except ValueError,e:
            writer.writerow(row)

The issue comes in the if/else statement. The 'if' statement works (as in the subtraction of 180), whereas the else statement will not work. The script runs fine, but it will eliminate all records with a value under 180 for some reason.

Where am I going wrong and how can I resolve this?

1 Answer 1

3

You don't write the row (writer.writerow(row) is missing) for that if block

if floatRow < 180.0:
    row[3] = floatRow + 180.0
    writer.writerow(row) # This is missing
else:
    writer.writerow(row)

Note: Since you are using if-else mainly to alter data for the row[3] column, I would suggest simplifying your script by moving the writer.writerow statements out and keeping only that altering logic within if-elif blocks

with open('in.csv', 'rb') as inp, open('out.csv', 'wb') as out:
    writer = csv.writer(out)
    for row in csv.reader(inp):
        try:
            floatRow= float(row[3].strip())
            if  floatRow > 180.0:
                row[3] = floatRow - 180.0
            elif floatRow < 180.0:
                row[3] = floatRow + 180.0
            writer.writerow(row)
        except ValueError,e:
            writer.writerow(row)
Sign up to request clarification or add additional context in comments.

4 Comments

That hurts my pride that I did not notice that. second pair of eyes are sometimes needed. Thank you.
@WillB We all make silly mistakes. Anyway, also check the edit.
I originally had it as your edit, but I was trying all sorts of different ways to make the if/else work because I was dumbfounded as to why it wasn't working. Thanks again!
@WillB If your query was resolved, don't forget to accept this ;)

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.