6

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?

Taras
35.8k5 gold badges77 silver badges151 bronze badges
asked Dec 3, 2017 at 8:28

2 Answers 2

6

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.

Taras
35.8k5 gold badges77 silver badges151 bronze badges
answered Dec 3, 2017 at 9:59
1
  • It was not valid Commented Dec 3, 2017 at 15:14
4

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

answered Dec 3, 2017 at 15:13

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.