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 QgsGeometry that is converted in QgsPoint to be printed as a tuple (inside the () parenthesis) of coordinates.

It is strongly recommended that you explore the preceding classes. You can also practice by referring to the documentation at http://qgis.org/api/. Start by exploring the QgisInterface and QGis classes.

Indentation is an important part of the Python language; in fact, nesting the code in Python is done using indentation, as specified in the standard followed globally. You can find this at http://legacy.python.org/dev/peps/pep-0008/.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.21.100.34