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