Reiion Reiion - 1 month ago 10
Python Question

Python iteration not entering if-elif

Pardon me if this is a really simple question. I've been at this for hours. I'm trying to read a csv file per row. However on the last row I don't want it to append any "," that's why I had separated the problem in an if-elif statement.

I'm not sure if this is just me sleepy but I can't seem to fix this simple matter. It doesn't enter in any condition yet when I print out the

print (iter, row_count , iter < row_count)
I'm 100% sure that the last row is False.

#read csv
data = csv.reader(open(csvFile, 'rb'), dialect='excel')

reader = csv.reader(open(csvFile, 'r'), delimiter=",")
tempData = list(reader)
row_count = len(tempData)


#geojson template
template = \
'''\
{
"type" : "Feature",
"id" : "%s",
"geometry" : {
"type" : "Point",
"coordinates" : [%s, %s]
},
"properties" : {
"name" : "%s"
}
}
'''

#head of geojson
output = \
'''
{ "type" : "FeatureCollection",
"features" : [
'''

#loop in csv
iter = 0

for row in data:
iter += 1
print (iter, row_count , iter < row_count)
if (iter < row_count == True):
print("TRUE")
id = row[0]
name = row[1]
latitude = row[2]
longitude = row[3]
output += template % (row[0], row[3], row[2], row[1])
output += ","
print (output)
elif (iter < row_count == False):
print("FALSE")
id = row[0]
name = row[1]
latitude = row[2]
longitude = row[3]
output += template % (row[0], row[3], row[2], row[1])
print (output)
#tail of geojson
output += \
'''\
]
}
'''

#open geojson file to write output
outFileHandler = open(geojsonFilePath, 'w')
outFileHandler.write(output)

print("Converted to geoJSON")
outFileHandler.close()

Answer
iter < row_count == True

and

iter < row_count == False

don't do what you think they do.

Python syntax allows chaining of comparisons, so something like

a < x < b

is equivalent to

(a < x) and (x < b)

This is a very handy feature, but it means that your iter < row_count == True is equivalent to

(iter < row_count) and (row_count == True)

So you should change that if statement to

if iter < row_count:

and change the elif to a plain else: