Saturday 29 August 2015

Python-OGR: nested loop only loops once


I have a polygon file buffer_stands.shp with 20 features and I have a line file OSMroads.geojson with 9 features.


I expected the script to loop through the buffers and print out for each buffer loop the the point count of each of the OSMroads. I know it doesn't sound useful, but the script is a simplification of a bigger script.


The outer loop loops all the way through. But the inner loop only loops once. What is causing that and how can I fix it?


import ogr

bufferfn = ogr.Open('buffer_stands.shp')
buffer_lyr = bufferfn.GetLayer()


roadfn = ogr.Open('OSMroads.geojson')
road_lyr = roadfn.GetLayer()

for buffer_feat in buffer_lyr:
buffer_geom = buffer_feat.GetGeometryRef()
print 'buffer'

for road_feat in road_lyr:
road_geom = road_feat.GetGeometryRef()

print road_geom.GetPointCount()



The output looks like this


>>> 
buffer
10
62
17
46

10
28
97
78
121
buffer
buffer
buffer
buffer
buffer

buffer
buffer
buffer
buffer
buffer
buffer
buffer
buffer
buffer
buffer

buffer
buffer
buffer
buffer

It shows the inner loop is running only once.



Answer



Use the ogr.Layer.ResetReading() method.


bufferfn = ogr.Open('buffer_stands.shp')
buffer_lyr = bufferfn.GetLayer()


roadfn = ogr.Open('OSMroads.geojson')
road_lyr = roadfn.GetLayer()

for buffer_feat in buffer_lyr:
buffer_geom = buffer_feat.GetGeometryRef()
print 'buffer'

for road_feat in road_lyr:
road_geom = road_feat.GetGeometryRef()

print road_geom.GetPointCount()

road_lyr.ResetReading() #Read the road layer from the beginning again

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...