[GIS] Iterating over features in vector layer

iterationpyqgis

Im trying to iterate over features in a vector layer following Iterating over Vector Layer:

from qgis.core import *
import qgis.utils
from qgis.core import QgsVectorLayer

shapefile = '/media/bera/Lagring/GIS/data/ok_riks_Sweref_99_TM_shape/oversikt/riks/ak_riks.shp'

layer = QgsVectorLayer(shapefile, 'borders', 'ogr')
it = layer.getFeatures()

for feature in it:
    geom = feature.geometry()
    print geom.type()
    print 'test'

print 'stop'

It will not go into the for block so all that is printed out is stop

The objects are created:

layer
<qgis._core.QgsVectorLayer object at 0x7fa08d2bcb98>
it
<qgis._core.QgsFeatureIterator object at 0x7fa08d32e218>

What am i doing wrong?

Best Answer

Check that the layer is valid. If the layer, or the path is not valid qgis will no raise an error, it will return a QgsVectorLayer object where you can call the methods but with mostly no-op.

layer = QgsVectorLayer(shapefile, 'borders', 'ogr')
if not layer.isValid():
    raise Exception('Layer is not valid')

It will be probably a bad path. Also try to open (manually) the file in qgis to check if there is any error with the shp.

Related Question