How do i iterate through a shapefile using shapely. This is my code but it keeps outputting the same id. I think that it keeps looking at the same record.

fc = fiona.open("file1.shp")
print fc.schema
for counter in range(0,50):    
    shapefile_record = fc.next()
    print shapefile_record['id']

1 Answer 1


fc.next() is a simple iterator:

fc = fiona.open("my.shp")
first_feature = fc.next()
second_feature = fc.next()

Or more simply:

for feat in fiona.open("my.shp")
     print feat

The result is a Python dictionary. For example with one result (feat=)

{'geometry': {'type': 'Point', 'coordinates': (180627.0, 330190.0)}, 'type': 'Feature', 'id': '154', 'properties': OrderedDict([(u'cadmium', 2.7), (u'copper', 27.0), (u'lead', 124.0), (u'zinc', 375.0), (u'elev', 8.261), (u'dist', 0.0122243), (u'om', 5.5), (u'ffreq', u'3'), (u'soil', u'3'), (u'lime', u'0'), (u'landuse', u'W'), (u'dist.m', 40.0)])}

As all dictionaries in Python, there are keys and values.

print feat.keys()
['geometry', 'type', 'id', 'properties']


print feat['id'] #gives the id
print feat['properties']['cadmium'] # gives the value of the cadmium attribute
print feat['geometry'] # gives the geometry, GeoJSON format
{'type': 'Point', 'coordinates': (180627.0, 330190.0)}

If you want to transform this geometry in a shapely geometry use the shape function:

print type(feat['geometry'])
<type 'dict'>
from shapely.geometry import shape
print shape(feat['geometry'])
POINT (180627 330190)
print type(shape(feat['geometry']))
<class 'shapely.geometry.point.Point'>


 with fiona.open("my.shp") as input:
     for feat in input:
         geom = shape(feat['geometry'])
         id = feat['id']
         cadmium = feat['properties']['cadmium']

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.