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?
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.