Im trying to iterate over features in a vector layer following Iterating over Vector Layer:
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?
2 Answers 2
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.
From Using PyQGIS in standalone scripts i added:
QgsApplication.setPrefixPath("/home/bera/.qgis2/", True) #Path to qgis installation
qgs = QgsApplication([], False)
qgs.initQgis()
#Script goes here
qgs.exitQgis()
And now it is working
Explore related questions
See similar questions with these tags.