My second PyQGIS code snippet – looping the layer features
In this paragraph, we'll introduce you to how to loop in Python and how to apply loops to explore the content of the layer loaded in the previous paragraph. Write the following snippet in the Python Console, taking special care with the code indentation:
for feature in layer.getFeatures(): print "Feature %d has attributes and geometry:" % feature.id() print feature.attributes() print feature.geometry().asPoint()
This will print a pattern like the following:
Feature with id 21 has attributes and geometry: [22, u'US00342', 858.0, u'Airport/Airfield', u'PATL', u'TATALINA LRRS', u' Other'] (-328415,4.71636e+06)
Note
The layer.getFeatures()
method returns an object that can be iterated inside a for
Python instruction, getting a QgsFeature
instance for every loop. The feature.attributes()
method returns a list (inside the brackets, []
) of the integer and Unicode strings (the u'
values). The feature.geometry()
method returns...